|
How to get/set values from servlet page to session object |
|
|
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:
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);
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.