This is a simple servlet that uses session tracking
and * Cookies to count the number of times a client session has *
accessed this servlet. */
public class Counter extends HttpServlet { // Define our counter
key into the session static final String COUNTER_KEY =
"Counter.count";
/** *
Performs the HTTP GET
operation * * @param req The request from the client * @param
resp The response from the servlet */
public void
doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException { // Get the session object
for this client session. // The parameter indicates to create a
session // object if one does not exist HttpSession session =
req.getSession(true);
// Set the content type of the
response resp.setContentType("text/html");
// Get the PrintWriter to write the response java.io.PrintWriter
out = resp.getWriter();
// Is there a count yet? int count = 1; Integer i =
(Integer) session.getValue(COUNTER_KEY);
// If a previous count exists, set it if (i != null)
{ count = i.intValue() + 1; }
// Put the count back into the
session session.putValue(COUNTER_KEY, new Integer(count));
//
Print a standard
header out.println(""); out.println("
"); out.println("Session
Counter"); out.println(""); out.println(""); out.println("Your
session ID is "
+ session.getId()); out.println(" and you have hit this
page " + count + " time(s) during this browser
session");
没有什么是永恒的,会话信息也不例外。所有的servlet引擎在会话保持一段时间的空闲之后,最终使它们无效。大多数引擎(Java Web
Servlet,ServletExec和JRun)都允许你配置这个超时时间的长度。一个会话无效时都会发生什么呢?首先,服务器将会释放该会话绑定的所有值,然后将会话对象释放,这样虚拟机就可以收集这些空间以便以后分配,后面我们还会看到如何得到一个对象解除其在会话中的绑定时的消息。
This servlet gathers all of the information about all
of * the sessions and returns a formatted table as part of a * form.
The user can then kill any of the sessions by * clicking a checkbox. This
servlet on functions * prior to version 2.1 of the Servlet API */
public class Killer extends HttpServlet { /** *
Performs the HTTP GET operation * * @param req The request
from the client * @param resp The response from the
servlet */ public void doGet(HttpServletRequest
req, HttpServletResponse resp) throws ServletException,
java.io.IOException { // Requesting more informatin about a
particular // session? String info =
req.getParameter("info"); if (info != null) { getInfo(info, req,
resp); return; }
// Set the content type of the
response resp.setContentType("text/html");
// Force the browser not to cache resp.setHeader("Expires", "Tues,
01 Jan 1980 00:00:00 GMT");
// Get the PrintWriter to write the
response java.io.PrintWriter out = resp.getWriter();
// Write the page
header out.println(""); out.println("
out.println("This page lists all of the current session
"); out.println("information. Check the session and press
"); out.println("'Kill' to remove the session. WARNING -
"); out.println("Killing an active session my cause problems
"); out.println("for some clients. ");
// If the user presses 'kill' send the request to
ourselves out.println("
req.getRequestURI() +
"">"); out.println("
"); out.println("
Kill
Session
ID
" + "
Last
Accessed
");
// Get the HttpSessionContext
object which holds // all of the session data HttpSession session
= req.getSession(true); HttpSessionContext context =
session.getSessionContext();
// Get the session IDs to kill String toKill[] =
req.getParameterValues("id"); if (toKill != null) {
// Loop
through and kill them for (int i = 0; i < toKill.length; i++)
{ HttpSession curSession =
context.getSession(toKill[i]);
// Invalidate the
session if (curSession != null)
{ getServletContext().log("Killing session "
+ curSession.getId()); curSession.invalidate(); } } }
//
Enumerate through the list of sessions java.util.Enumeration enum =
context.getIds(); while (enum.hasMoreElements()) { String
sessionID = (String) enum.nextElement();
// Format the table
entry out.println("
"value="" + sessionID +
"">
"); out.println("
"?info=" + sessionID + "">"
+ sessionID + "
");
// Get the last time accessed String time =
""; HttpSession curSession = context.getSession(sessionID); if
(curSession != null) { long last =
curSession.getLastAccessedTime(); time = (new
java.util.Date(last)).toString(); } out.println("
//
Wrap
up out.println(""); out.println(""); out.flush(); }
/** *
Displays a page with detailed session info *
@param id The session id * @param req The request from the client *
@param resp The response from the servlet */ public void
getInfo(String id, HttpServletRequest req, HttpServletResponse
resp) throws ServletException, java.io.IOException { // Set
the content type of the
response resp.setContentType("text/html");
// Force the
browser not to cache resp.setHeader("Expires", "Tues, 01 Jan 1980
00:00:00 GMT");
// Get the PrintWriter to write the
response java.io.PrintWriter out = resp.getWriter();
// Write the page
header out.println(""); out.println("
// Get the HttpSessionContext object which holds // all of the
session data HttpSession session =
req.getSession(true); HttpSessionContext context =
session.getSessionContext();
// Attempt to find the session HttpSession curSession =
context.getSession(id); if (curSession == null)
{ out.println("Session " + id + " not found"); } else
{
out.println("
Information for session "
+ id + "
");
// Display a table with all of the
info out.println("
");
// Creation time long creationTime =
curSession.getCreationTime(); out.println("
Creation
Time
" + (new java.util.Date(creationTime))
+ "
");
// Last accessed
time long lastTime =
curSession.getLastAccessedTime(); out.println("
Last
Access Time
" + (new java.util.Date(lastTime))
+ "
");
out.println("
");
// Get an array of value
names String names[] = curSession.getValueNames();
if ((names != null) && (names.length > 0))
{ out.println("
Bound objects
");
// Display a table with all of the bound
values out.println("
");
for (int i = 0; i < names.length; i++)
{ out.println("
" + names[i] +
"
" + curSession.getValue(names[i])
+ "
"); } out.println("
"); }
out.println("
"); }
// Wrap
up out.println(""); out.println(""); out.flush(); }
This is a simple servlet that displays all of
the * Cookies present in the request */ public class Cookies
extends HttpServlet {
/** *
Performs the HTTP GET
operation * * @param req The request from the client * @param
resp The response from the servlet */ public void
doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException {
// Set the content type
of the response resp.setContentType("text/html");
// Get the PrintWriter to write the response java.io.PrintWriter
out = resp.getWriter();
// Get an array containing all of the cookies Cookie cookies[] =
req.getCookies();
// Write the page
header out.println(""); out.println("
This is a simple servlet that uses session tracking
* and URL rewriting to count the number of times a client session *
has accessed this servlet. */
public class CounterRewrite extends HttpServlet { // Define our
counter key into the session static final String COUNTER_KEY =
"CounterRewrite.count";
/** *
Performs the HTTP GET operation * *
@param req The request from the client * @param resp The response from the
servlet */
public void doGet(HttpServletRequest
req, HttpServletResponse resp) throws ServletException,
java.io.IOException { // Set the content type of the
response resp.setContentType("text/html");
// Get the PrintWriter to write the response java.io.PrintWriter
out = resp.getWriter();
// Get the session HttpSession session = req.getSession(true);
// Is there a count yet? int count = 1; Integer i =
(Integer) session.getValue(COUNTER_KEY);
// If a previous count exists, set it if (i != null)
{ count = i.intValue() + 1; }
// Put the count back into the
session session.putValue(COUNTER_KEY, new Integer(count));
//
Print a standard
header out.println(""); out.println("
"); out.println("Session
Counter " + "with URL
rewriting"); out.println(""); out.println(""); out.println("Your
session ID is "
+ session.getId()); out.println(" and you have hit this
page " + count + " time(s) during this
browser session");
// Format the URL String url = req.getRequestURI(); //+ ";" +
SESSION_KEY + //session.getId();
// Wrap
up out.println(""); out.println(""); out.flush(); }
/** *
Performs the HTTP GET operation * * @param req The request
from the client * @param resp The response from the
servlet */ public void doPost(HttpServletRequest
req, HttpServletResponse resp) throws ServletException,
java.io.IOException { // Same as get request doGet(req,
resp); } } 图6.8 CounterRewrite.java代码清单
This servlet shows how to send a session count *
to a client using data input/output streams. */
public class CounterJava extends HttpServlet { // Define our
counter key into the session static final String COUNTER_KEY =
"CounterJava.count";
/** *
Services the HTTP
request * * @param req The request from the client * @param
resp The response from the servlet */ public void
service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, java.io.IOException { // Get the
session HttpSession session = req.getSession(true);
// Is there a count yet? int count = 1; Integer i =
(Integer) session.getValue(COUNTER_KEY);
// If a previous count exists, set it if (i != null)
{ count = i.intValue() + 1; }
// Put the count back into the
session session.putValue(COUNTER_KEY, new Integer(count));
//
Get the input stream for reading data from the client DataInputStream in
= new DataInputStream(req.getInputStream());
// We'll be sending binary data back to the client so // set the
content type
appropriately resp.setContentType("application/octet-stream");
// Data will always be written to a byte array buffer so // that
we can tell the client the length of the data ByteArrayOutputStream
byteOut = new ByteArrayOutputStream();
// Create the output stream to be used to write the // data to our
buffer DataOutputStream out = new DataOutputStream(byteOut);
// If there is any data being sent from the client, // read it
here
// Write the data to our internal buffer. out.writeInt(count);
// Flush the contents of the output stream to the // byte
array out.flush();
// Get the buffer that is holding our response byte[] buf =
byteOut.toByteArray();
// Notify the client how much data is being
sent resp.setContentLength(buf.length);
// Send the buffer to the client ServletOutputStream servletOut =
resp.getOutputStream();
// Wrap
up servletOut.write(buf); servletOut.close(); } } 图6.10
CounterJava.java代码清单
This application shows how maintain cookies
manually * by using a simple counter servlet */
public class CounterApp { // The servlet url String
m_url;
// The value of the session cookie String m_cookie =
null;
/** *
Application entry point. This application
requires * one parameter, which is the servlet URL */ public
static void main(String args[]) { // Make sure we have an argument
for the servlet URL if (args.length == 0)
{ System.out.println("
Servlet URL must be
specified"); return; }
try {
// Create a new object CounterApp app = new
CounterApp(args[0]);
// Get the count multiple times for (int i = 1; i <=5; i++)
{ int count = app.getCount(); System.out.println("Pass " + i +
" count=" + count); } } catch (Exception ex)
{ ex.printStackTrace(); }
}
/** * Construct a new CounterApp object * @param url The
servlet url */ public CounterApp(String url) { m_url =
url; }
/** * Invokes a counter servlet and returns the hit
count * that was returned by the servlet */ public int
getCount() throws Exception { // Get the server URL
java.net.URL url = new java.net.URL(m_url);
// Attempt to
connect to the host java.net.URLConnection con =
url.openConnection();
// Set the session ID if necessary if
(m_cookie != null) { con.setRequestProperty("cookie",
m_cookie); }
// Initialize the
connection con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true);
// Data will always be written to a byte array buffer so // that
we can tell the server the length of the data ByteArrayOutputStream
byteOut = new ByteArrayOutputStream();
// Create the output stream to
be used to write the // data to our buffer DataOutputStream out =
new DataOutputStream(byteOut);
// Send any data to the servlet
here
// Flush the data to the
buffer out.flush();
// Get our buffer to be sent byte
buf[] = byteOut.toByteArray();
// Set the content that we are
sending con.setRequestProperty("Content-type", "application/octet-stream");
//
Set the length of the data buffer we are
sending con.setRequestProperty("Content-length", "" +
buf.length);
// Get the output stream to the server and send
our // data buffer DataOutputStream dataOut = new
DataOutputStream(con.getOutputStream()); dataOut.write(buf);
//
Flush the output stream and close
it dataOut.flush(); dataOut.close();
// Get the input
stream we can use to read the response DataInputStream in = new
DataInputStream(con.getInputStream());
// Read the data from the
server int count = in.readInt();
// Close the input
stream in.close();
// Get the session cookie if we haven't already if (m_cookie ==
null) { String cookie = con.getHeaderField("set-cookie"); if
(cookie != null) { m_cookie =
parseCookie(cookie); System.out.println("Setting session ID=" +
m_cookie); } }
return count; }
/** * Parses the given cookie and returns the cookie key * and
value. For simplicity the key/ value is assumed * to be before the first
';', as in: * * jrunsessionid=3509823408122; path=/ * *
@param rawCookie The raw cookie data * @return The key/value of the
cookie */ public String parseCookie(String
raw) { String c = raw;
if (raw != null) {
// Find the first ';' int endIndex = raw.indexOf(";");
// Found a ';', assume the key/value is prior if (endIndex >=
0) { c = raw.substring(0,
endIndex); } }
This is a simple servlet that binds an object
that * implements the HttpSessionBindingListener interface. */
public class Binder extends HttpServlet { /** *
Performs the HTTP GET operation * * @param req The request
from the client * @param resp The response from the
servlet */
public void doGet(HttpServletRequest
req, HttpServletResponse resp) throws ServletException,
java.io.IOException { // Set the content type of the
response resp.setContentType("text/html");
// Get the PrintWriter to write the response java.io.PrintWriter
out = resp.getWriter();
// Get the session object for this client session. // The
parameter indicates to create a session // object if one does not
exist HttpSession session = req.getSession(true);
// Create a new SessionObject SessionObject o = new
SessionObject();
// Put the new SessionObject into the
session session.putValue("Binder.object", o);
// Print a
standard
header out.println(""); out.println("
This object demonstrates the use of the *
HttpSessionBindingListener interface. */
public class SessionObject implements
HttpSessionBindingListener {
/** * Called when this object is bound into a session. *
@param event The event */ public void
valueBound(HttpSessionBindingEvent event) { // Output the fact that
we are being bound System.out.println("" + (new java.util.Date())
+ " Binding " + event.getName() + " to session "
+ event.getSession().getId()); }
/** * Called when
this object is unbound from a session * @param event The
event */ public void valueUnbound(HttpSessionBindingEvent
event) { // Output the fact that we are being
bound System.out.println("" + (new java.util.Date()) + "
Unbinding " + event.getName() + " from session "
+ event.getSession().getId()); } } 图6.14
SessionObject.java代码清单