Session management in servlet.

   In normal java web application the user name and other user related information are stored it into session and displayed into all the user pages. The best example is user name, because you need to display the user name into all the pages. It is achieved in following ways. Note the session management is very important in java application because the performance of the application based on the session management. So don't save unnecessary information into session. The following example gives one small idea about session management in java web application.
  In this application I have created one java class for storing user related information. Because instead of using more keys for storing values into session, I have created the one java class and I have stored this class object into session (UserResults). This is good practice for storing values into session.

1. Create a UserResults class and include the following code. This class basically created for the purpose of storing user related information. In future I can able to add some more variable for storing some other information.

package com.results;

public class UserResults {
    public String userName;
}

2. Create a simple servlet and include the following code. Here I am using my LoginController servlet.

package com.controller;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.results.UserResults;
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginController() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
         HttpSession session = request.getSession(true);
        if((userName.equals("admin") && password.equals("admin"))){
            // Creating object for UserResults
            UserResults userResults = new UserResults();
           // Storing user name into userName variable.
            userResults.userName = userName;
           // Storing userResults object into session
            session.setAttribute("userResults", userResults);
            //Redirect to success page.
            response.sendRedirect("success.jsp");
        }
        else{
            //Redirect error page.
            response.sendRedirect("loginfailure.jsp");
        }
    }
}

The session.setAttribute(key,value) method in servlet is used for storing key,value pair into session.

3. If user name and password are admin then this servlet allow user to access your information. Here I am redirecting it into success,jsp page. So include the following code into success.jsp.
<%@page import="com.results.UserResults"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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 Success</title>
</head>
<body>
        <%
            // Getting userResult object from session.
            UserResults userResult = (UserResults)session.getAttribute("userResults");
        %>
    <!-- Displaying user name -->
    <h3>Welcome Mr <%= userResult.userName%>     </h3>
</body>
</html>

The session.getAttribute(key) method in servlet is used for getting value from session based on key.

4. Run this application and logged in as admin, you can able to get the out put like this.






5. If you want to delete the session variable from session then use session.removeAttribute(key as String) method.
   session.removeAttribute("userResults");
6. If you want to close the session of particular user then, do like this.
     Get the corresponding user session handle through
         HttpSession session = request.getSession(true);
     Then call session.invalidate() function. This function used for removing all the object associated with that particular user from session as well remove the user session from server.

Comments