Skip to main content

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

Popular posts from this blog

Ext JS 4 – Creating web page using Ext.container.Viewport class and region propery

The Ext.container.Viewport is used for creating general web page and region property is used for splitting web page into different parts. Ext.container.Viewport is a specialized container represents the viewable area of the application (the browser area). It render itself to the document body, there is no need for providing renderTo property and it automatically sizes itself to size of the browser viewport. The viewport also re-size the child elements based on view area(based on browser width and height). The default layout of the viewport is border layout and we can customize this property according to our requirements. The viewport does not provide any scrolling. If necessary, the child elements(generally panels) within viewport needs to provide a scroll feature by using autoScroll property. See the below example for better understanding. This is Home.js file placed into app/view folder. Ext.define('MyApp.view.Home', { extend : 'Ext.container.Viewport&#

Getting servlet init parameter that is defined in web.xml

1. Create a new dynamic web project using eclipse. 2. Create a one new servlet and include the following code. package com.controller ; import java.io.IOException; import javax.servlet .ServletConfig; import javax.servlet .ServletException; import javax.servlet .annotation.WebServlet; import javax.servlet .http.HttpServlet; import javax.servlet .http.HttpServletRequest; import javax.servlet .http.HttpServletResponse; @ 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 {                                 ServletConfig config = getServletConfig ();                                 System.out.println( "Init parameter user nam

Simple Login Application Using Spring MVC and Hibernate – Part 1

 I hope developers working in web application development might hear about MVC architecture. Almost all technologies provide support for MVC based web application development, but the success is based on many factors like reusable of the code, maintenance of the code, future adaption of the code, etc..,  The success of the Spring MVC is “ Open for extension and closed for modification ” principle. Using Spring MVC the developers can easily develop MVC based web application. We don’t need any steep learning curve at the same time we need to know the basics of spring framework and MVC architecture. The Spring MVC consists of following important components. 1. Dispatcher servlet 2. Controller 3. View Resolver 4. Model Spring MVC - Overview  The overall architecture of Spring MVC is shown here.  1. When “Dispatcher Servlet” gets any request from client, it finds the corresponding mapped controller for the request and just dispatches the request to the corresponding contro