Session Management in Java

List of Files

  1. header.jsp
  2. login.jsp
  3. home.jsp
  4. logout.jsp

header.jsp

<a href="login.jsp">Login</a>
<a href="home.jsp">Home</a>
<a href="logout.jsp">Logout</a>

 


login.jsp

 

<%
    HttpSession sess = request.getSession();

    if (sess.getAttribute("sess_username") != null) { // check is session variable exist in session pool or not
        response.sendRedirect("home.jsp"); // if session variable is already set then redirect it to home page else stay on login page
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Login</h1>
        <form action="home.jsp" method="post">
            Username <input type="text" name="username"/><br/>
            Password <input type="password" name="password"/><br/>
            <input type="submit" value="Login"/>
        </form>
    </body>
</html>

 


home.jsp

 

<%
    HttpSession sess = request.getSession(); //get the session object from getSession() method of request object

    if (sess.getAttribute("sess_username") == null) { // check whether the session variable is exist in session pool or not
        sess.setAttribute("sess_username", request.getParameter("username")); // create session variable if it is not present in session pool
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Home</h1>
        <h2>Hello <%=sess.getAttribute("sess_username")%> </h2>
    </body>
</html>

 


logout.jsp

 

<%
    HttpSession sess = request.getSession();
    sess.invalidate(); // this will terminate the session and destroy all variables stored in session pool
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Logout</h1>
    </body>
</html>

 


Display Session variables from pool

Console o/p:

 

Enumeration attributeNames = sess.getAttributeNames();

while (attributeNames.hasMoreElements()) {

    String name = (String) attributeNames.nextElement();

    String value = (String) sess.getAttribute(name);

    out.println(name + "=" + value);

}

 

JSTL(Java Server Pages Standard Tag Library) o/p:

<c:forEach var="session" items="${sessionScope}">

    ${session.key} = ${session.value}

</c:forEach>

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *