Monday, December 24, 2012

Session Tracking using HttpSession Interface


To recognize particular user we create a session and bind that user with that session object. For every new user, program creates a new session and the same thing we are doing here we are creating a session during user login. If user exists in the database then page will redirect to valid page and a session will generate else it'll redirect to Invalid page.

If you copy valid page url to another browser then it'll redirect it to index.jsp page because we are checking whether session is null or not.

public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.

On Valid.java page our create is false and if we try to go to this page directly then null will redirect it to index.jsp page.
 
Project View After Completion
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;  

HttpSession Interface and Methods  :

public interface HttpSession
Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. 


public HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one. 


public void setAttribute(String name, Object value)
Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced.


public Object getAttribute(String name)
Returns the object bound with the specified name in this session, or null if no object is bound under the name. 


HttpSession 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 {  
   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())  
       {  
         HttpSession session=req.getSession();  
         session.setAttribute("user", s1);  
         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();  
     HttpSession session=request.getSession(false);  
     if(session==null)  
     {  
       response.sendRedirect("index.jsp");  
      }  
  else  
     {  
       String name=(String)session.getAttribute("user");  
       out.println("<h1>Welcome!"+ name +"</h1>");  
      }  
    }   
 }  

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();  
       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>");  
     }  
 }  

Download Code Link 1
Download Code Link 2

Output:

No comments:

Popular Posts