Use URL rewrite to save session data

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerRewrite extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();

out.println(“<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>”);
out.println(“<BODY>”);

// Get the current session ID, or generate one if necessary
String sessionid = req.getPathInfo();
if (sessionid == null) {
sessionid = generateSessionId();
}

// Cart items are associated with the session ID
String[] items = getItemsFromCart(sessionid);

// Print the current cart items.
out.println(“You currently have the following items in your cart:<BR>”);
if (items == null) {
out.println(“<B>None</B>”);
} else {
out.println(“<UL>”);
for (int i = 0; i < items.length; i++) {
out.println(“<LI>” + items[i]);
}
out.println(“</UL>”);
}

// Ask if the user wants to add more items or check out.
// Include the session ID in the action URL.
out.println(“<FORM ACTION=\”/servlet/ShoppingCart/” + sessionid + “\” METHOD=POST>”);
out.println(“Would you like to<BR>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Add More Items \”>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Check Out \”>”);
out.println(“</FORM>”);

// Offer a help page. Include the session ID in the URL.
out.println(“For help, click <A href=\”/servlet/Help/” + sessionid
+ “?topic=ShoppingCartViewerRewrite\”>here</A>”);

out.println(“</BODY></HTML>”);
}

private static String generateSessionId() throws UnsupportedEncodingException {
String uid = new java.rmi.server.UID().toString(); // guaranteed unique
return URLEncoder.encode(uid, “UTF-8”); // encode any special chars
}

private static String[] getItemsFromCart(String sessionid) {
return new String[] { “a”, “b” };
}
}
=============================

Using Sessions in Servlet

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

public class UsingSessions extends HttpServlet
{

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);

Integer counter = (Integer) session.getAttribute(“counter”);

if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}

session.setAttribute(“counter”, counter);

out.println(“<HTML>”);
out.println(“<HEAD>”);
out.println(“<TITLE>”);
out.println(“Using Sessions”);
out.println(“</TITLE>”);
out.println(“</HEAD>”);
out.println(“<BODY>”);
out.println(“<H1>Using Sessions</H1>”);

out.println(“Welcome! You have been here ” + counter + ” times.<BR>”);

if(session.isNew()){
out.println(“This is a new session.<BR>”);
} else {
out.println(“This is not a new session.<BR>”);
}

out.println(“The session ID: ” + session.getId() + “<BR>”);
out.println(“Last time accessed: ” + new Date(session.getLastAccessedTime()) + “<BR>”);
out.println(“Creation time: ” + new Date(session.getCreationTime()) + “<BR>”);
out.println(“Timeout length: ” + session.getMaxInactiveInterval() + ” seconds<BR>”);

out.println(“</BODY>”);
out.println(“</HTML>”);
}
}

====================================================================

Session Tracker

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionTracker extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException
{
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();

HttpSession session = req.getSession(true);

Integer count = (Integer) session.getAttribute(“count”);

if (count == null) {
count = new Integer(1);
} else {
count = new Integer(count.intValue() + 1);
}

session.setAttribute(“count”, count);
out.println(“<html><head><title>SessionSnoop</title></head>”);
out.println(“<body><h1>Session Details</h1>”);
out.println(“You’ve visited this page ” + count + ((count.intValue()== 1) ? ” time.” : ” times.”) + “<br/>”);
out.println(“<h3>Details of this session:</h3>”);
out.println(“Session id: ” + session.getId() + “<br/>”);
out.println(“New session: ” + session.isNew() + “<br/>”);
out.println(“Timeout: ” + session.getMaxInactiveInterval() + “<br/>”);
out.println(“Creation time: ” + new Date(session.getCreationTime()) + “<br/>”);
out.println(“Last access time: ” + new Date(session.getLastAccessedTime()) + “<br/>”);
out.println(“</body></html>”);
}
}
===========================

session
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SimpleSession extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {

response.setContentType(“text/html”);
java.io.PrintWriter out = response.getWriter();
HttpSession session = request.getSession();

out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Simple Session Tracker</title>”);
out.println(“</head>”);
out.println(“<body>”);

out.println(“<h2>Session Info</h2>”);
out.println(“session Id: ” + session.getId() + “<br><br>”);
out.println(“The SESSION TIMEOUT period is ”
+ session.getMaxInactiveInterval() + ” seconds.<br><br>”);
out.println(“Now changing it to 20 minutes.<br><br>”);
session.setMaxInactiveInterval(20 * 60);
out.println(“The SESSION TIMEOUT period is now ”
+ session.getMaxInactiveInterval() + ” seconds.”);

out.println(“</body>”);
out.println(“</html>”);

}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request
*            servlet request
* @param response
*            servlet response
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {

doGet(request, response);
}

}
==============================================

session listener

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListen implements HttpSessionListener {

private int sessionCount;

public SessionListen() {
this.sessionCount = 0;
}

public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
session.setMaxInactiveInterval(60);
synchronized (this) {
sessionCount++;
}
String id = session.getId();
Date now = new Date();
String message = new StringBuffer(“New Session created on “).append(
now.toString()).append(“\nID: “).append(id).append(“\n”)
.append(“There are now “).append(“” + sessionCount).append(
” live sessions in the application.”).toString();

System.out.println(message);
}

public void sessionDestroyed(HttpSessionEvent se) {

HttpSession session = se.getSession();
String id = session.getId();
synchronized (this) {
–sessionCount;
}
String message = new StringBuffer(“Session destroyed”
+ “\nValue of destroyed session ID is”).append(“” + id).append(
“\n”).append(“There are now “).append(“” + sessionCount)
.append(” live sessions in the application.”).toString();
System.out.println(message);
}
}
==============================================

session filter

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

private FilterConfig config;

/** Creates new SessionFilter */
public SessionFilter() {
}

public void init(FilterConfig filterConfig) throws ServletException {

System.out.println(“Instance created of ” + getClass().getName());
this.config = filterConfig;
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {

HttpSession session = ((HttpServletRequest) request).getSession();
ServletContext context = config.getServletContext();
/*
* use the ServletContext.log method to log filter messages
*/
context.log(“doFilter called in: ” + config.getFilterName() + ” on ”
+ (new java.util.Date()));

// log the session ID
context.log(“session ID: ” + session.getId());

// Find out whether the logged-in session attribute is set
String logged = (String) session.getAttribute(“logged-in”);
if (logged == null)
session.setAttribute(“logged-in”, “no”);

//log a message about the log-in status
context.log(“log-in status: ”
+ (String) session.getAttribute(“logged-in”));
context.log(“”);
chain.doFilter(request, response);
}

public void destroy() {
/*
* called before the Filter instance is removed from service by the web
* container
*/
}
}

======================================

session bind listener

mport java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class SessionBindListen implements HttpSessionBindingListener {

private Map info;

/** Creates new SessionBindListen */
public SessionBindListen() {

//zero-arg constructor
info = new HashMap();
}

public void valueBound(HttpSessionBindingEvent be) {

HttpSession session = be.getSession();
String id = session.getId();
String name = be.getName();
Object value = be.getValue();
String source = be.getSource().getClass().getName();
String message = new StringBuffer(“Attribute bound to session in “)
.append(source).append(“\nThe attribute name: “).append(name)
.append(“\n”).append(“The attribute value: “).append(value)
.append(“\n”).append(“The session id: “).append(id).toString();

System.out.println(message);
}

public void valueUnbound(HttpSessionBindingEvent be) {

HttpSession session = be.getSession();
String id = session.getId();
String name = be.getName();
if (name == null)
name = “Unknown”;
String source = be.getSource().getClass().getName();
String message = new StringBuffer(“Attribute unbound from session in “)
.append(source).append(“\nThe attribute name: “).append(name)
.append(“\n”).append(“The session id: “).append(id).toString();
//clear Map; send message
info.clear();
System.out.println(message + “\nThe size of the HashMap is: ”
+ info.size());
}

public void addInfo(String name, String email) {

info.put(email, name);

}

}
=======================================

use cookies to save session data

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();

String sessionid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(“sessionid”)) {
sessionid = cookies[i].getValue();
break;
}
}
}

// If the session ID wasn’t sent, generate one.
// Then be sure to send it to the client with the response.
if (sessionid == null) {
sessionid = generateSessionId();
Cookie c = new Cookie(“sessionid”, sessionid);
res.addCookie(c);
}

out.println(“<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>”);
out.println(“<BODY>”);

// Cart items are associated with the session ID
String[] items = getItemsFromCart(sessionid);

// Print the current cart items.
out.println(“You currently have the following items in your cart:<BR>”);
if (items == null) {
out.println(“<B>None</B>”);
} else {
out.println(“<UL>”);
for (int i = 0; i < items.length; i++) {
out.println(“<LI>” + items[i]);
}
out.println(“</UL>”);
}

// Ask if they want to add more items or check out.
out.println(“<FORM ACTION=\”/servlet/ShoppingCart\” METHOD=POST>”);
out.println(“Would you like to<BR>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Add More Items \”>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Check Out \”>”);
out.println(“</FORM>”);

// Offer a help page.
out.println(“For help, click <A href=\”/servlet/Help”
+ “?topic=ShoppingCartViewerCookie\”>here</A>”);

out.println(“</BODY></HTML>”);
}

private static String generateSessionId() throws UnsupportedEncodingException {
String uid = new java.rmi.server.UID().toString(); // guaranteed unique
return URLEncoder.encode(uid,”UTF-8″); // encode any special chars
}

private static String[] getItemsFromCart(String sessionid) {
return new String[]{“a”,”b”};
}
}

=============================

use hidden field to save data

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerHidden extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();

out.println(“<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>”);
out.println(“<BODY>”);

// Cart items are passed in as the item parameter.
String[] items = req.getParameterValues(“item”);

// Print the current cart items.
out.println(“You currently have the following items in your cart:<BR>”);
if (items == null) {
out.println(“<B>None</B>”);
}
else {
out.println(“<UL>”);
for (int i = 0; i < items.length; i++) {
out.println(“<LI>” + items[i]);
}
out.println(“</UL>”);
}

// Ask if the user wants to add more items or check out.
// Include the current items as hidden fields so they’ll be passed on.
out.println(“<FORM ACTION=\”/servlet/ShoppingCart\” METHOD=POST>”);
if (items != null) {
for (int i = 0; i < items.length; i++) {
out.println(“<INPUT TYPE=HIDDEN NAME=\”item\” VALUE=\”” +
items[i] + “\”>”);
}
}
out.println(“Would you like to<BR>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Add More Items \”>”);
out.println(“<INPUT TYPE=SUBMIT VALUE=\” Check Out \”>”);
out.println(“</FORM>”);

out.println(“</BODY></HTML>”);
}
}

=========================

session display

import java.text.DateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionDisplay extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {

response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Date creationTime = new Date(session.getCreationTime());
Date lastAccessed = new Date(session.getLastAccessedTime());
Date now = new Date();
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.MEDIUM);

out.println("<html>");
out.println("<head>");
out.println("<title>Displaying the Session Creation and Last-Accessed Time</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Session Creation and Last-Accessed Time</h2>");
out.println("The time and date now is: " + formatter.format(now)
+ "<br><br>");
out.println("The session creation time: HttpSession.getCreationTime( ): "
+ formatter.format(creationTime) + "<br><br>");
out.println("The last time the session was accessed: HttpSession.getLastAccessedTime( ): "
+ formatter.format(lastAccessed));
out.println("</body>");
out.println("</html>");

}
}

Leave a Reply