Session Tracking using Cookies

Http is a stateless protocol so that it can't maintain user's state or can't recognize that request is coming from same user to server so that to maintain user's state we are using Session Tracking with the help of Cookie Class.

Project View


Create login table and insert data into login table using insert command and here we are using Oracle10g database(you can also use other database)
 create table login ( id number,  
 uname varchar2(20),  
 upass varchar2(20)  
 );  


 insert into login values (1,'him','him123');  
 commit;  

Cookie Class and Methods

public class Cookie extends Object implements Cloneable
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.


public Cookie(String name, String value)
Constructs a cookie with the specified name and value. 

public void addCookie(Cookie cookie)
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.


public Cookie[] getCookies()

Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent. 


public String getName()

Returns the name of the cookie. The name cannot be changed after creation. 


public String getValue()
Gets the current value of this Cookie. 


public int getMaxAge()
Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until browser shutdown.


public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie. 

Cookie Example:

index.jsp
This is page for user's view  and on submit action is run1
 <html>  
  <head>  
   <title></title>  
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  </head>  
  <body><center>  
    <h1>Application Form</h1>  
    <form action="run1" method="get">  
      <table>  
        <tr>  
          <td>User Name : </td>  
          <td><input type="text" name="t1"></td>  
        </tr>  
        <tr>  
          <td>Password : </td>  
          <td><input type="password" name="t2"></td>  
        </tr>  
        <tr>  
          <td>  
            <input type="submit" value="Sign In"/>  
          </td>  
        </tr>  
      </table>  
    </form>  
    </center></body>  
 </html>  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
   <servlet>  
     <servlet-name>LoginServlet</servlet-name>  
     <servlet-class>LoginServlet</servlet-class>  
   </servlet>  
   <servlet>  
     <servlet-name>Invalid</servlet-name>  
     <servlet-class>Invalid</servlet-class>  
   </servlet>  
   <servlet>  
     <servlet-name>Valid</servlet-name>  
     <servlet-class>Valid</servlet-class>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>LoginServlet</servlet-name>  
     <url-pattern>/run1</url-pattern>  
   </servlet-mapping>  
   <servlet-mapping>  
     <servlet-name>Invalid</servlet-name>  
     <url-pattern>/Invalid</url-pattern>  
   </servlet-mapping>  
   <servlet-mapping>  
     <servlet-name>Valid</servlet-name>  
     <url-pattern>/Valid</url-pattern>  
   </servlet-mapping>  
   <session-config>  
     <session-timeout>  
       30  
     </session-timeout>  
   </session-config>  
   <welcome-file-list>  
     <welcome-file>index.jsp</welcome-file>  
   </welcome-file-list>  
 </web-app>  

LoginServlet.java
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.*;  
 import java.sql.*;  
 public class LoginServlet extends HttpServlet {  
   @Override  
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
     resp.setContentType("text/html");  
     PrintWriter out=resp.getWriter();  
     String s1=req.getParameter("t1");  
     String s2=req.getParameter("t2");  
     try  
     {  
       Class.forName("oracle.jdbc.driver.OracleDriver");  
       Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");  
       Statement st=con.createStatement();  
       ResultSet rs=st.executeQuery("select * from login where uname='"+s1+"' and upass='"+s2+"'");  
       if(rs.next())  
       {  
         Cookie c=new Cookie("name",s1);  
         resp.addCookie(c);  
         resp.sendRedirect("Valid");  
       }  
  else  
       {  
         resp.sendRedirect("Invalid");  
        }  
     }  
     catch(Exception e)  
     {  
       out.println(e);  
     }  
   }  
  }  

Valid.java
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.*;  
 public class Valid extends HttpServlet {  
   protected void service(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
     response.setContentType("text/html;charset=UTF-8");  
     PrintWriter out = response.getWriter();  
     try {  
       Cookie c[]=request.getCookies();  
       if(c==null)  
       {  
         response.sendRedirect("index.jsp");  
       }  
  else  
       {  
         out.println("<h1>Welcome!"+c[0].getValue()+"</h1>");  
  }  
     } finally {   
       out.close();  
     }  
   }   
 }  

Invalid.java
 import java.io.IOException;  
 import java.io.PrintWriter;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 public class Invalid extends HttpServlet {  
   protected void service(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
     response.setContentType("text/html;charset=UTF-8");  
     PrintWriter out = response.getWriter();  
     try {  
       out.println("<html>");  
       out.println("<head>");  
       out.println("<title>Servlet Invalid</title>");   
       out.println("</head>");  
       out.println("<body>");  
       out.println("<h1>Invalid User!</h1>");  
       out.println("</body>");  
       out.println("</html>");  
     } finally {   
       out.close();  
     }  
   }   
 }  
Download Code Link 1
Download Code Link 2


Output:


More Servlet Topics :

No comments: