Explain HttpSession using Servlet and JSP with example?


            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.

 

            The servlet container uses this interface to create a session between an HTTP client and an HTTP server.

            The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times.

 

This interface allows servlets to

             View and manipulate information about a session, such as the session identifier, creation time, and last accessed time

            Bind objects to sessions, allowing user information to persist across multiple user connections

 

Creating a session

 HttpSession session=request.getSession();

                or

HttpSession session=request.getSession(true);

            True ? return existing session object or it will create new Session if there is no session available

            False ? return the existing session, if there is no session available it returns null

 

Example

Creating a session

 package com.candidjava;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class RegistrationController
 */
public class RegistrationController extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String name=request.getParameter("name");
		String email=request.getParameter("email");
		
		HttpSession session=request.getSession(true);
		session.setAttribute("name", name);
		session.setAttribute("email", email);
		
		response.sendRedirect("success.jsp");
		
	}

}

Fetching the session

 <%@page session="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
String name=(String)session.getAttribute("name");
String email=(String)session.getAttribute("email");

%>

Entered Name is <b> <%=name %></b> <br>
Entered Email is <b><%=email %></b>
<br>
<br>
Thanks for visiting candidjava.com...

</body>
</html>


Screenshot

            

            


Download

                HttpSessionexample war

                HttpSessionexample zip



Related Post

Comments


©candidjava.com