Home » Java Codes

Java Servlet – How to get/set values from servlet page to session object

12 February 2009 941 views One Comment

Applications like UserManagement, Shopping Cart etc require to store values in cache so that when a user returns his information is restored from cache.

There are three ways to implement sessions in Java Servlets:

  • Cookies: HTTP Cookies to store information. Methods response.addCookie(cookie) will add cookie and request.getCookies() will return value of cookies.
  • URL Rewriting: Append data on the end of each URL that identifies the session like http://localhost/yourservlet?session-id=value.
  • Hidden form fields: HTML forms can have
    <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">.

Example below displays the session information like how many time user has accessed the page, session id, creation time etc.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

public class sessionServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
String title = “Session Information Servlet”;
String heading;
int cnt =0;
if (session.isNew())
{
heading = “Welcome, New”;
}
else
{
heading = “Welcome Back”;
int oldcnt = (int)session.getValue(“accessCount”);
if (oldcnt != null)
{
cnt =oldcnt + 1;
}
}
session.putValue(“accessCount”, cnt);

out.println(ServletUtilities.headWithTitle(title) +
“<H1 ALIGN=\”CENTER\”>” + heading + “</H1>\n” +
“<TABLE BORDER=1 ALIGN=CENTER>\n” +
“<TR>\n” +
“  <TD>ID\n” +
“  <TD>” + session.getId() + “\n” +
“<TR>\n” +
“  <TD>Creation Time\n” +
“  <TD>” + new Date(session.getCreationTime()) + “\n” +
“<TR>\n” +
“  <TD>Time of Last Access\n” +
“  <TD>” + new Date(session.getLastAccessedTime()) + “\n” +
“<TR>\n” +
“  <TD>Number of Accesses\n” +
“  <TD>” + accessCount + “\n” +
“</TABLE>\n” +
“</BODY></HTML>”);

}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}


Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

One Comment »

  • Mehmet said:

    Good information.thank you very much.

Leave your response!

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>