Java/Servlets/Session
Содержание
- 1 Fake session
- 2 Map adaptor for HttpSession objects
- 3 Servlet: session attribute listener
- 4 Servlet: Session bind listener
- 5 Servlet: Session display
- 6 Servlet Session Example
- 7 Servlet : session filter
- 8 Servlet: session listener
- 9 Servlet: simple session
- 10 Session Events: implements HttpSessionBindingListener
- 11 Session Expiration Filter
- 12 Session logger
- 13 Session Tracker
- 14 Use cookie to save session data
- 15 Use hidden fields to save session data
- 16 Use URL rewrite to save session data
- 17 Using Sessions in Servlet
Fake session
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
/**
* For the benefit of anyone that wants to create a fake HttpSession
* that doesn"t do anything other than not be null.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class FakeHttpSession implements HttpSession
{
/**
* Setup the creation time
*/
public FakeHttpSession()
{
creationTime = System.currentTimeMillis();
}
/**
* Setup the creation time
* @param id The new session id
*/
public FakeHttpSession(String id)
{
this.id = id;
creationTime = System.currentTimeMillis();
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getCreationTime()
*/
public long getCreationTime()
{
return creationTime;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getId()
*/
public String getId()
{
if (id == null)
{
System.out.println("Inventing data in FakeHttpSession.getId() to remain plausible.");
id = "fake";
}
return id;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getLastAccessedTime()
*/
public long getLastAccessedTime()
{
return creationTime;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getServletContext()
*/
public ServletContext getServletContext()
{
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int)
*/
public void setMaxInactiveInterval(int maxInactiveInterval)
{
this.maxInactiveInterval = maxInactiveInterval;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getMaxInactiveInterval()
*/
public int getMaxInactiveInterval()
{
return maxInactiveInterval;
}
/**
* @see javax.servlet.http.HttpSession#getSessionContext()
* @deprecated
*/
@SuppressWarnings({"UnnecessaryFullyQualifiedName"})
@Deprecated
public javax.servlet.http.HttpSessionContext getSessionContext()
{
return null;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getAttribute(java.lang.String)
*/
public Object getAttribute(String name)
{
return attributes.get(name);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getValue(java.lang.String)
*/
@Deprecated
public Object getValue(String name)
{
return attributes.get(name);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getAttributeNames()
*/
public Enumeration<String> getAttributeNames()
{
return Collections.enumeration(attributes.keySet());
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#getValueNames()
*/
@Deprecated
public String[] getValueNames()
{
return attributes.keySet().toArray(new String[attributes.keySet().size()]);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#setAttribute(java.lang.String, java.lang.Object)
*/
public void setAttribute(String name, Object value)
{
attributes.put(name, value);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#putValue(java.lang.String, java.lang.Object)
*/
@Deprecated
public void putValue(String name, Object value)
{
attributes.put(name, value);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String)
*/
public void removeAttribute(String name)
{
attributes.remove(name);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#removeValue(java.lang.String)
*/
@Deprecated
public void removeValue(String name)
{
attributes.remove(name);
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#invalidate()
*/
public void invalidate()
{
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpSession#isNew()
*/
public boolean isNew()
{
return true;
}
/**
* The session id
*/
private String id = null;
/**
* The list of attributes
*/
private Map<String, Object> attributes = new HashMap<String, Object>();
/**
* When were we created
*/
private long creationTime;
/**
* How long before we timeout?
*/
private int maxInactiveInterval = 30 * 60 * 1000;
}
Map adaptor for HttpSession objects
/*
* Copyright 2004-2005 Malcolm A. Edgar
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpSession;
/**
* Provides a Map adaptor for HttpSession objects. A SessionMap instance is
* available in each Velocity page using the name "<span class="blue">session</span>".
* <p/>
* For example suppose we have a User object in the session with the
* attribute name "user" when a user is logged on. We can display the users
* name in the page when the are logged onto the system.
*
* <pre class="codeHtml">
* <span class="red">#if</span> (<span class="blue">$session</span>.user)
* <span class="blue">$session</span>.user.fullname you are logged on.
* <span class="red">#else</span>
* You are not logged on.
* <span class="red">#end</span> </pre>
*
* The ClickServlet adds a SessionMap instance to the Velocity Context before
* it is merged with the page template.
* <p/>
* The SessionMap supports {@link FlashAttribute} which when accessed via
* {@link #get(Object)} are removed from the session.
*
* @author Malcolm.Edgar
*/
public class SessionMap implements Map {
/** The internal session attribute. */
protected HttpSession session;
/**
* Create a <tt>HttpSession</tt> <tt>Map</tt> adaptor.
*
* @param value the http session
*/
public SessionMap(HttpSession value) {
session = value;
}
/**
* @see java.util.Map#size()
*/
public int size() {
if (session != null) {
int size = 0;
Enumeration enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
enumeration.nextElement();
size++;
}
return size;
} else {
return 0;
}
}
/**
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* @see java.util.Map#containsKey(Object)
*/
public boolean containsKey(Object key) {
if (session != null && key != null) {
return session.getAttribute(key.toString()) != null;
} else {
return false;
}
}
/**
* This method is not supported and will throw
* <tt>UnsupportedOperationException</tt> if invoked.
*
* @see java.util.Map#containsValue(Object)
*/
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
/**
* If the stored object is a FlashObject this method will return the
* FlashObject value and then remove it from the session.
*
* @see java.util.Map#get(Object)
*/
public Object get(Object key) {
if (session != null && key != null) {
Object object = session.getAttribute(key.toString());
if (object instanceof FlashAttribute) {
FlashAttribute flashObject = (FlashAttribute) object;
object = flashObject.getValue();
session.removeAttribute(key.toString());
}
return object;
} else {
return null;
}
}
/**
* @see java.util.Map#put(Object, Object)
*/
public Object put(Object key, Object value) {
if (session != null && key != null) {
Object out = session.getAttribute(key.toString());
session.setAttribute(key.toString(), value);
return out;
} else {
return null;
}
}
/**
* @see java.util.Map#remove(Object)
*/
public Object remove(Object key) {
if (session != null && key != null) {
Object out = session.getAttribute(key.toString());
session.removeAttribute(key.toString());
return out;
} else {
return null;
}
}
/**
* @see java.util.Map#putAll(Map)
*/
public void putAll(Map map) {
if (session != null && map != null) {
for (Iterator i = map.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
session.setAttribute(key, value);
}
}
}
/**
* @see java.util.Map#clear()
*/
public void clear() {
if (session != null) {
Enumeration enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement().toString();
session.removeAttribute(name);
}
}
}
/**
* @see java.util.Map#keySet()
*/
public Set keySet() {
if (session != null) {
Set keySet = new HashSet();
Enumeration enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
keySet.add(enumeration.nextElement());
}
return keySet;
} else {
return Collections.EMPTY_SET;
}
}
/**
* This method is not supported and will throw
* <tt>UnsupportedOperationException</tt> if invoked.
*
* @see java.util.Map#values()
*/
public Collection values() {
throw new UnsupportedOperationException();
}
/**
* @see java.util.Map#entrySet()
*/
public Set entrySet() {
if (session != null) {
Set entrySet = new HashSet();
Enumeration enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement().toString();
Object value = session.getAttribute(name);
entrySet.add(value);
}
return entrySet;
} else {
return Collections.EMPTY_SET;
}
}
}
Servlet: session attribute listener
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionAttribListen implements HttpSessionAttributeListener {
/** Creates new SessionAttribListen */
public SessionAttribListen() {
System.out.println(getClass().getName());
}
public void attributeAdded(HttpSessionBindingEvent se) {
HttpSession session = se.getSession();
String id = session.getId();
String name = se.getName();
String value = (String) se.getValue();
String source = se.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 attributeRemoved(HttpSessionBindingEvent se) {
HttpSession session = se.getSession();
String id = session.getId();
String name = se.getName();
if (name == null)
name = "Unknown";
String value = (String) se.getValue();
String source = se.getSource().getClass().getName();
String message = new StringBuffer("Attribute unbound from 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 attributeReplaced(HttpSessionBindingEvent se) {
String source = se.getSource().getClass().getName();
String message = new StringBuffer("Attribute replaced in session ")
.append(source).toString();
System.out.println(message);
}
}
Servlet: Session bind listener
import 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);
}
}
Servlet: 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>");
}
}
Servlet Session Example
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: SessionExample.java,v 1.4 2004/03/18 16:40:33 jfarcand Exp $
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson <duncan@eng.sun.ru>
*/
public class SessionExample extends HttpServlet {
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body bgcolor=\"white\">");
out.println("<head>");
String title = rb.getString("sessions.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body>");
// img stuff not req"d for source code html showing
// relative links everywhere!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("");
out.println("</body>");
out.println("</html>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* HTML filter utility.
*
* @author Craig R. McClanahan
* @author Tim Tye
* @version $Revision: 1.2 $ $Date: 2004/03/18 16:40:34 $
*/
final class HTMLFilter {
/**
* Filter the specified message string for characters that are sensitive in
* HTML. This avoids potential attacks caused by including JavaScript codes
* in the request URL that is often reported in error messages.
*
* @param message
* The message string to be filtered
*/
public static String filter(String message) {
if (message == null)
return (null);
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case "<":
result.append("<");
break;
case ">":
result.append(">");
break;
case "&":
result.append("&");
break;
case """:
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
}
Servlet : 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
*/
}
}
Servlet: 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);
}
}
Servlet: simple 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 Events: implements HttpSessionBindingListener
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class Binder extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(true);
SessionObject o = new SessionObject(getServletContext());
session.setAttribute("Binder.object", o);
out.println("<html>");
out.println("<head>");
out.println("<title>Session Binder</title>");
out.println("</head>");
out.println("<body>");
out.println("Object bound to session " + session.getId());
out.println("</body>");
out.println("</html>");
out.flush();
}
}
class SessionObject implements HttpSessionBindingListener {
ServletContext context;
public SessionObject(ServletContext context) {
this.context = context;
}
public void valueBound(HttpSessionBindingEvent event) {
context.log("" + (new java.util.Date()) + " Binding " + event.getName() + " to session "
+ event.getSession().getId());
}
public void valueUnbound(HttpSessionBindingEvent event) {
context.log("" + (new java.util.Date()) + " Unbinding " + event.getName() + " from session "
+ event.getSession().getId());
}
}
Session Expiration Filter
/*
************************************************************************************
* Copyright (C) 2008-2009 Openbravo S.L.
* Licensed under the Apache Software License version 2.0
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
************************************************************************************
*/
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionExpirationFilter implements Filter {
public void init(FilterConfig config) {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest hReq = (HttpServletRequest) req;
HttpSession session = hReq.getSession(false);
if (null != session) {
Date expirationDate = (Date) session.getAttribute("expirationDate");
if (expirationDate == null)
expirationDate = new Date(System.currentTimeMillis() + 1000000); // only
// for
// make
// false
// "expirationDate.before(new Date())"
// in
// the
// first
// execution
if (expirationDate.before(new Date())) {
session.invalidate();
session = null;
} else {
// ignore requests marked as both ajaxCall and ignoreForSessionTimeout
String isAjaxCall = hReq.getParameter("IsAjaxCall");
String ignoreForSessionTimeout = hReq.getParameter("ignoreForSessionTimeout");
boolean ignoreForTimeout = "1".equals(isAjaxCall) && ("1".equals(ignoreForSessionTimeout));
if (ignoreForTimeout) {
// Do nothing; don"t update the session timestamp
} else {
session.setAttribute("expirationDate", new Date(System.currentTimeMillis()
+ session.getMaxInactiveInterval() * 1000));
}
}
}
chain.doFilter(req, resp);
}
public void destroy() {
}
}
Session logger
//Log4j from Apache is required
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionLogger implements HttpSessionListener {
private Logger log;
public SessionLogger() {
/*
* The loggers are typically initialized by a special initialization
* listener or servlet. If this is not the case, then initialize the
* logger here:
*
* java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle(
* "com.jexp.global");
* PropertyConfigurator.configure(bundle.getString(
* "log-configure-path"));
*/
log = Logger.getLogger(SessionLogger.class);
}
public void sessionCreated(HttpSessionEvent se) {
//log request of the INFO level
log.info("HttpSession created: " + se.getSession().getId());
}
public void sessionDestroyed(HttpSessionEvent se) {
//log request about session"s that are invalidated
log.info("HttpSession invalidated: " + se.getSession().getId());
}
}
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>");
}
}
Use cookie 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 ");
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"};
}
}
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>");
}
}
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 ");
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" };
}
}