Thursday, July 5, 2018

URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??


Advantage of URL Rewriting:
  • It will always work whether cookie is disabled or not (browser independent).
  • Extra form submission is not required on each pages.

Disadvantage of URL Rewriting:
  • It will work only with links.
  • It can send Only textual information.

Hidden Form Field

we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.

<input type="hidden" name="uname" value="Bharath">

Advantage of Hidden Form Field:
  • It will always work whether cookie is disabled or not.
 Disadvantage of Hidden Form Field:
  • It is maintained at server side.
  • Extra form submission is required on each pages.
  • Only textual information can be used.

Cookies in Servlet


A cookie is a small piece of information that is persisted between the multiple client requests.

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of cookies in servlets:
  • Non-persistent cookie
  • Persistent cookie
Non-persistent cookie:

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie:

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or sign out.

Advantage of Cookies:
  • Simplest technique of maintaining the state.
  • Cookies are maintained at client side.
Disadvantage of Cookies:
  • It will not work if cookie is disabled from the browser.
  • Only textual information can be set in Cookie object.
 Cookie class:
javax.servlet.http.Cookie

Constructor of Cookie class:

Constructor
Description
Cookie()
constructs a cookie.
Cookie(String name, String value)
constructs a cookie with a specified name and value.

Useful Methods of Cookie class:


Method
Description
public void setMaxAge(int expiry)
Sets the maximum age of the cookie in seconds.
public String getName()
Returns the name of the cookie. The name cannot be changed after creation.
public String getValue()
Returns the value of the cookie.
public void setName(String name)
changes the name of the cookie.
public void setValue(String value)
changes the value of the cookie.


Other methods required for using Cookies:


For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:
  1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
  2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.
Create Cookie:

Cookie ck=new Cookie("user","sonoo jaiswal"); //creating cookie object 
response.addCookie(ck); //adding cookie in the response

Delete Cookie:

Cookie ck=new Cookie("user",""); //deleting value of cookie 
ck.setMaxAge(0); //changing the maximum age to 0 seconds 
response.addCookie(ck); //adding cookie in the response

Get Cookies:

Cookie ck[]=request.getCookies(); 
for(int i=0;i<ck.length;i++){ 
 out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie 
}

Session Tracking Techniques

There are four techniques used in Session tracking:
  • Cookies
  • Hidden Form Field
  • URL Rewriting
  • HttpSession

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>