Tuesday, June 26, 2018

Attribute in Servlet


An attribute in servlet is an object that can be set, get or removed from one of the following scopes:
  1.     request scope
  2.     session scope
  3.    application scope
  • The servlet programmer can pass informations from one servlet to another using attributes.
  • It is just like passing object from one class to another so that we can reuse the same object again and again. 
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:

  1. public void setAttribute(String name,Object object):sets the given object in the application scope.
  2. public Object getAttribute(String name):Returns the attribute for the specified name.
  3. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 
  4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
Example:
 DemoServlet1

ServletContext context=getServletContext(); 
context.setAttribute("company","IBM");


DemoServlet2


ServletContext context=getServletContext(); 
String n=(String)context.getAttribute("company");



Difference between ServletConfig and ServletContext
 
The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application.

ServletContext Interface


  • An object of ServletContext is created by the web container at time of deploying the project.
  • This object can be used to get configuration information from web.xml file.
  • There is only one ServletContext object per web application.
  • If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
  • If the information is changed in web.xml, we don't need to modify the servlet.
  • The ServletContext object can be used to set, get or remove attribute from the web.xml file.
    The ServletContext object can be used to provide inter-application communication.
 Commonly used methods of ServletContext interface
  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects..
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the attribute for the specified name.
  5. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
Syntax to call the methods of ServletContext interface


    //We can get the ServletContext object from ServletConfig object 
    ServletContext application=getServletConfig().getServletContext(); 
     
    //Another convenient way to get the ServletContext object 
    ServletContext application=getServletContext();


Syntax to provide the initialization parameter in Context scope

<web-app> 
 ...... 
     
  <context-param> 
    <param-name>parametername</param-name> 
    <param-value>parametervalue</param-value> 
  </context-param> 
 ...... 
</web-app>


Example of ServletContext to get the initialization parameter

In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don't need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element.

DemoServlet.java

    import java.io.*; 
    import javax.servlet.*; 
    import javax.servlet.http.*; 
     
     
    public class DemoServlet extends HttpServlet{ 
    public void doGet(HttpServletRequest req,HttpServletResponse res) 
    throws ServletException,IOException 
    { 
    res.setContentType("text/html"); 
    PrintWriter pw=res.getWriter(); 
     
    //creating ServletContext object 
    ServletContext context=getServletContext(); 
     
    //Getting the value of the initialization parameter and printing it 
    String driverName=context.getInitParameter("drivername"); 
    pw.println("driver name is="+driverName); 
     
    pw.close(); 
     
    }}


web.xml

    <web-app> 
     
    <servlet> 
    <servlet-name>
DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
    </servlet> 
     
    <context-param> 
    <param-name>drivername</param-name> 
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> 
    </context-param> 
     
    <servlet-mapping> 
    <servlet-name>
DemoServlet</servlet-name> 
    <url-pattern>/context</url-pattern> 
    </servlet-mapping> 
     
    </web-app> 


Example of ServletContext to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class. 

DemoServlet.java

    import java.io.*; 
    import javax.servlet.*; 
    import javax.servlet.http.*; 
     
     
    public class DemoServlet extends HttpServlet{ 
    public void doGet(HttpServletRequest req,HttpServletResponse res) 
    throws ServletException,IOException 
    { 
    res.setContentType("text/html"); 
    PrintWriter out=res.getWriter(); 
     
    ServletContext context=getServletContext(); 
    Enumeration<String> e=context.getInitParameterNames(); 
         
    String str=""; 
    while(e.hasMoreElements()){ 
        str=e.nextElement(); 
        out.print("<br> "+context.getInitParameter(str)); 
    } 
    }}


web.xml

    <web-app> 
     
    <servlet> 
    <servlet-name>
DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
    </servlet> 
     
    <context-param> 
    <param-name>dname</param-name> 
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> 
    </context-param> 
     
    <context-param> 
    <param-name>username</param-name> 
    <param-value>system</param-value> 
    </context-param> 
     
    <context-param> 
    <param-name>password</param-name> 
    <param-value>oracle</param-value> 
    </context-param> 
     
    <servlet-mapping> 
    <servlet-name>
DemoServlet</servlet-name> 
    <url-pattern>/context</url-pattern> 
    </servlet-mapping> 
     
    </web-app>


 

Servlet Config Interface


  • An object of ServletConfig is created by the web container for each servlet.
  • This object can be used to get configuration information from web.xml file.
  •  If the configuration information is modified from the web.xml file, we don't need to change the servlet.
Methods of Servlet Config Interface

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
  3. public String getServletName():Returns the name of the servlet.
  4. public ServletContext getServletContext():Returns an object of ServletContext.
Syntax to Call the methods of ServletConfig interface

ServletConfig config=getServletConfig();  

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

<web-app> 
  <servlet> 
    ...... 
     
    <init-param> 
      <param-name>parametername</param-name> 
      <param-value>parametervalue</param-value> 
    </init-param> 
    ...... 
  </servlet> 
</web-app>


 Example of ServletConfig to get initialization parameter

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.


DemoServlet.java

    import java.io.*; 
    import javax.servlet.*; 
    import javax.servlet.http.*; 
     
    public class DemoServlet extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException { 
     
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
         
        ServletConfig config=getServletConfig(); 
        String driver=config.getInitParameter("driver"); 
        out.print("Driver is: "+driver); 
             
        out.close(); 
        } 
     
    }  


Web.xml

<web-app> 
     
    <servlet> 
    <servlet-name>DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
     
    <init-param> 
    <param-name>driver</param-name> 
    <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> 
    </init-param> 
     
    </servlet> 
     
    <servlet-mapping> 
    <servlet-name>DemoServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
    </servlet-mapping> 
     
    </web-app>


Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java

    import java.io.IOException; 
    import java.io.PrintWriter; 
    import java.util.Enumeration; 
     
    import javax.servlet.ServletConfig; 
    import javax.servlet.ServletException; 
    import javax.servlet.http.HttpServlet; 
    import javax.servlet.http.HttpServletRequest; 
    import javax.servlet.http.HttpServletResponse; 
     
     
    public class DemoServlet extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
     
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
         
        ServletConfig config=getServletConfig(); 
        Enumeration<String> e=config.getInitParameterNames(); 
             
        String str=""; 
        while(e.hasMoreElements()){ 
        str=e.nextElement(); 
        out.print("<br>Name: "+str); 
        out.print(" value: "+config.getInitParameter(str)); 
        } 
             
        out.close(); 
    } 
     
    }


Web.xml

<web-app> 
     
    <servlet> 
    <servlet-name>DemoServlet</servlet-name> 
    <servlet-class>DemoServlet</servlet-class> 
     
    <init-param> 
    <param-name>username</param-name> 
    <param-value>system</param-value> 
    </init-param> 
     
    <init-param> 
    <param-name>password</param-name> 
    <param-value>oracle</param-value> 
    </init-param> 
     
    </servlet> 
     
    <servlet-mapping> 
    <servlet-name>DemoServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
    </servlet-mapping> 
     
    </web-app>  

Request Dispatcher

  • The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.
  • This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.  

Two Methods of Request Dispatcher:
  1. Forward
  2. Include

    Syntax:
              RequestDispatcher rd = request.getRequestDispatcher("/URL Pattern of Destination Servlet");
              rd.forward(request,response);   //Forward
              rd.include(request,response);    //Include
     
    Send Redirect
    • The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.  

    Syntax:
              response.sendRedirect("/URL Pattern of Destination Servlet");    //Redirect


    forward() method
    sendRedirect() method
    The forward() method works at server side.
    The sendRedirect() method works at client side.
    It sends the same request and response
    objects to another servlet.
    It always sends a new request.
    It can work within the server only.
    It can be used within and outside the server.


    Note: 
    • In Forward and Include, the URL will not change.
    • In Redirect URL will be changed.