Friday, 11 September 2015

HTTP SESSION

HttpSession


java.servlet.http Package

1. The classes and interfaces of javax.servlet.http package handle servlets that communicates using HTTP.
2. These servlets are also called as HTTP servlets.
3. The following are the commonly used interfaces of the javax.servlet.http package:
a) HttpServletRequest Interface
b) HttpServletResponse Interface 
c) HttpSession Interface 

HttpSession Interface

The HttpSession interface contains methods to maintain the state of an end user across a Web application.
An object of the HttpSession interface provides support for tracking and managing the session of an end user.

The following describes various methods of the HttpSession interface:
1. public void setAttribute (String name, Object value)
Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then this method replaces the existing attribute.

2. public Object getAttribute(String name)
Retrieves the String object specified in the parameter ,from the session object . If no object is found for the specified attribute , then the getAttribute() method returns null.

3. public Enumeration getAttributeNames ()
Returns an Enumeration that contains the name of the all the objects that are bound as attribute to the session object.

Basic Functioning of Session




Creating Simple Program in Servlet for using Session.In this we will receive data from index.jsp and make it global object by Session and after that call it in welcome.jsp.

Step 1 : Create index.jsp with two fields and form action.

1
<%@page contentType="text/html" pageEncoding="UTF-8"%>
2
<!DOCTYPE html>
3
<html>
4
    <head>
5
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
        <title>JSP Page</title>
7
    </head>
8
    <body>
9
              <h>HTTP SERVLET SESSION</h>
10
        <form action="javat">
11
            <pre>
12
            USERNAME : <input type="text" name="name">
13
14
            PASSWORD : <input type="password" name="pass"> 
15
16
                       <input type="submit" value="submit">
17
            </pre>
18
        </form>    
19
    </body>
20
</html>
21
22
23
    


Step 2 : Create a new file web.xml under WebContent/WEB-INF folder and write below code.

1
<?xml version="1.0" encoding="UTF-8" ?> 
2
<web-app version="3.0" 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_3_0.xsd">
3
<servlet>
4
  <servlet-name>login</servlet-name> 
5
  <servlet-class>com.javat.sessionDemo.login</servlet-class> 
6
  </servlet>
7
<servlet-mapping>
8
  <servlet-name>login</servlet-name> 
9
  <url-pattern>/javat</url-pattern> 
10
  </servlet-mapping>
11
<session-config>
12
  <session-timeout>30</session-timeout> 
13
  </session-config>
14
  </web-app>
15
    


Step 3 : Create a package com.javat.SessionDemo under Java resources-> src folder and then create the servlet class Login.java. Once you ready then write the code given below.
In this code we will receive data from index page and store in variables after that make it Global.

1
/*
2
* To change this template, choose Tools | Templates
3
* and open the template in the editor.
4
*/
5
package com.javat.sessionDemo;
6
7
import java.io.IOException;
8
import java.io.PrintWriter;
9
import javax.servlet.RequestDispatcher;
10
import javax.servlet.ServletException;
11
import javax.servlet.http.HttpServlet;
12
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletResponse;
14
import javax.servlet.http.HttpSession;
15
16
/**
17
 *
18
 * @author ORANITIN
19
 */
20
public class login extends HttpServlet {
21
22
    /**
23
     * Processes requests for both HTTP
24
     * <code>GET</code> and
25
     * <code>POST</code> methods.
26
     *
27
     * @param request servlet request
28
     * @param response servlet response
29
     * @throws ServletException if a servlet-specific error occurs
30
     * @throws IOException if an I/O error occurs
31
     */
32
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
33
            throws ServletException, IOException {
34
        response.setContentType("text/html;charset=UTF-8");
35
        PrintWriter out = response.getWriter();
36
        
37
        String name=request.getParameter("name");
38
        String pass=request.getParameter("pass");
39
        
40
        if(name.equalsIgnoreCase("admin") && pass.equalsIgnoreCase("123"))
41
        {
42
              HttpSession sec=request.getSession();   
43
              sec.setAttribute("name",name);
44
              RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
45
              rd.forward(request, response);
46
        }
47
        else
48
        {
49
            response.sendRedirect("index.jsp");
50
            
51
        }
52
        
53
        
54
        try {
55
            /* TODO output your page here. You may use following sample code. */
56
            out.println("<html>");
57
            out.println("<head>");
58
            out.println("<title>Servlet login</title>");            
59
            out.println("</head>");
60
            out.println("<body>");
61
            out.println("<h1>Servlet login at " + request.getContextPath() + "</h1>");
62
            out.println("</body>");
63
            out.println("</html>");
64
        } finally {            
65
            out.close();
66
        }
67
    }
68
69
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
70
    /**
71
     * Handles the HTTP
72
     * <code>GET</code> method.
73
     *
74
     * @param request servlet request
75
     * @param response servlet response
76
     * @throws ServletException if a servlet-specific error occurs
77
     * @throws IOException if an I/O error occurs
78
     */
79
    @Override
80
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
81
            throws ServletException, IOException {
82
        processRequest(request, response);
83
    }
84
85
    /**
86
     * Handles the HTTP
87
     * <code>POST</code> method.
88
     *
89
     * @param request servlet request
90
     * @param response servlet response
91
     * @throws ServletException if a servlet-specific error occurs
92
     * @throws IOException if an I/O error occurs
93
     */
94
    @Override
95
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
96
            throws ServletException, IOException {
97
        processRequest(request, response);
98
    }
99
100
 /**
101
 * Returns a short description of the servlet.
102
 *
103
 * @return a String containing servlet description
104
 */
105
    @Override
106
    public String getServletInfo() {
107
        return "Short description";
108
    }// </editor-fold>
109
}
110
111
112
    



Step 4: Create a new file welcome.jsp under Webpages and write the code given below.
Call the data that we have Stored using Session.

1
<%@page contentType="text/html" pageEncoding="UTF-8"%>
2
<!DOCTYPE html>
3
<html>
4
    <head>
5
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6
        <title>JSP Page</title>
7
    </head>
8
    <body>
9
        <%
10
        HttpSession sec=request.getSession(false);
11
        String name=(String)sec.getAttribute("name");
12
        out.println("welcome you : "+name);
13
        %>
14
   </body>
15
</html>
16
17
18
19
20
21
    

No comments:

Post a Comment