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

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

Getting key/value pair from JSON object and getting variable name and value from JavaScript object.

 Hi, I had faced one issue like this. I have an JSON object but I don't know any key name but I need to get the all the key and corresponding value from JSON object using client side JavaScript. Suddenly I wondered whether it's possible or not, after that I had done lot of workaround and finally got this solution. See the below example.    function getKeyValueFromJSON() {     var jsonObj =  {a:10,b:20,c:30,d:50} ;     for ( var key in jsonObj) {       alert( "Key: " + key + " value: " + jsonObj[key]);     }  }  In this example I have created the one json array as string, and converted this string into JSON object using eval() function. Using for-each loop I got all the key value from jsonObj, and finally using that key I got the corresponding value.  Finally I got the alert like this,    Key: a value:10    Key: b value:20    Key: c value:30    Key: d value:50  During this workaround I got one more idea, using this same way I got

Simple Login Application Using Spring MVC and Hibernate – Part 2

 I hope you have visited my part1 of my tutorial . Let’s see the steps for integrating hibernate framework into Spring MVC. Here I have used MySQL database. I have created one database called “ springmvc ” and created one table called “ user ” with userid, username, password fields.  I have inserted some records into table like this. Step 1: Creating User POJO class.  We need to create a User POJO class for mapping user table. Ok let’s create it. Step 2: Creating hibernate mapping xml file for user class.  In hibernate we need to create hibernate mapping xml file for all domain class for mapping into corresponding database table. Instead of creating xml file you can use annotation for mapping domain class into database table. This is my mapping xml document created for mapping our user domain class into user database table. Step 3: Creating authenticate service class.  The method “verifyUserNameAndPassword” present in “AuthenticateService”