HttpSession in servlet

HttpSession:

HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session id is given to the user when first request comes. This id is stored in a request parameter or in a cookie.

How to get session object?

HttpServletRequest interface’s getSession() method is used to get the session object.

Syntax:

HttpSession session = request.getSession();  

How to set attribute in session object?

HttpSession interface’s setAttribute() method is used to set attribute in session object.

Syntax:

public void setAttribute(String name,Object value);

Example:

session.setAttribute("attName", "attValue"); 

How to get attribute from session object?

HttpSession interface’s getAttribute() method is used to get attribute from session object.

Syntax:

public Object getAttribute(String name);

Example:

String value = (String) session.getAttribute("attName"); 

Session management example using HttpSession:

LoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
/**
* This class is used to set values in session.
* @author w3spoint
*/
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
   //no-argument constructor
    public LoginServlet() {
 
    }
 
    protected void doPost(HttpServletRequest request, 
    	   HttpServletResponse response)
                   throws ServletException, IOException {
	response.setContentType("text/html"); 
    	PrintWriter out = response.getWriter();
 
    	//get parameters from request object.
    	String userName = request.getParameter("userName").trim();
    	String password = request.getParameter("password").trim();
 
    	//check for null and empty values.
    	if(userName == null || userName.equals("") || 
    			password == null || password.equals("")){
    		out.print("Please enter both username " +
    				"and password. <br/><br/>");
    		RequestDispatcher requestDispatcher = 
    			request.getRequestDispatcher("/login.html");
    		requestDispatcher.include(request, response);
    	}//Check for valid username and password.
    	else if(userName.equals("jai") && password.equals("1234")){
    		HttpSession session=request.getSession();  
                session.setAttribute("userName",userName);  
                session.setAttribute("password",password);
    		out.println("Logged in successfully.<br/>"); 
    		out.println("Click on the below link to see " +
    			"the values of Username and Password.<br/>");
    		out.println("<a href='DisplaySessionValueServlet'>" +
    				"Click here</a>");
    	    out.close();
    	}else{
    		out.print("Wrong username or password. <br/><br/>");
    		RequestDispatcher requestDispatcher = 
    			request.getRequestDispatcher("/login.html");
    		requestDispatcher.include(request, response);
    	}
    }
}

DisplaySessionValueServlet.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;
import javax.servlet.http.HttpSession;
 
/**
* This class is used to get values from session.
* @author w3spoint
*/
public class DisplaySessionValueServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    //no-argument constructor
    public DisplaySessionValueServlet() {
 
    }
 
    protected void doGet(HttpServletRequest request, 
	    HttpServletResponse response)
	             throws ServletException, IOException {
	response.setContentType("text/html"); 
    	PrintWriter out = response.getWriter();
 
    	//get parameters from session object.
    	HttpSession session=request.getSession(false);  
        String userName =(String)session.getAttribute("userName");  
        String password =(String)session.getAttribute("password");  
 
    	out.println("Username: " + userName + "<br/><br/>");
    	out.println("Password: " + password);
 
    	out.close();
    }
}

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
	<form action="LoginServlet" method="post">
		Username:<input type="text" name="userName"/>
		<br/><br/>
		Password:<input type="password" name="password"/>
		<br/><br/> 
		<input type="submit" value="login"/> 
	</form>  
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>
    	com.w3spoint.business.LoginServlet
    </servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
 
  <servlet>
    <servlet-name>DisplaySessionValueServlet</servlet-name>
    <servlet-class>
    	com.w3spoint.business.DisplaySessionValueServlet
    </servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>DisplaySessionValueServlet</servlet-name>
    <url-pattern>/DisplaySessionValueServlet</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
 
</web-app>

Session management example using HttpSession:

servlet example 13 login
 
Enter username: jai and password: 1234
servlet example 13 value
 
Click on login button.
servlet example 13 link
 
Click on the link.
servlet example 13 show value
 
Download this example.
 
Next Topic: Servlet filter in java with example.
Previous Topic: URL rewriting in servlet with example.

 

Content Protection by DMCA.com
Please Share