Java Tutorial/Servlet/Session
Содержание
Get Set SessionAttributes in Servlet
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
Integer count = (Integer)session.getAttribute("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
out.println("You"ve visited this page " + count +
((count.intValue() == 1) ? " time." : " times."));
out.println("<P>");
out.println("<H2>Here is your session data:</H2>");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("</BODY></HTML>");
}
}
Get Set Session Value in a Servlet
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet 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 counter2 = (Integer) getServletContext().getAttribute ("counter2");
if (counter2 == null) {
counter2 = new Integer(1);
} else {
counter2 = new Integer(counter2.intValue() + 1);
}
getServletContext().setAttribute("counter2", counter2);
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 Contexts");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<H1>Using Contexts</H1>");
out.println("Welcome! You have been here " + counter + " times.<BR>");
out.println("Total page accesses: " + counter2 + "<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>");
}
}
Servlet Session Check
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.DateFormat;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(false);
if (session == null){
response.sendRedirect("/dbproj/login.jsp");
} else {
response.sendRedirect("/dbproj/menu.jsp");
}
}
}
Servlet Session Creation Last Access Time
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.DateFormat;
public class MyServlet 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 Info
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet 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);
}
}
Servlet Session Max Inactive Interval
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
out.println("<BODY><H1>Session Timer</H1>");
// Display the previous timeout
out.println("The previous timeout was " +
session.getMaxInactiveInterval());
out.println("<BR>");
// Set the new timeout
session.setMaxInactiveInterval(2*60*60); // two hours
// Display the new timeout
out.println("The newly assigned timeout is " +
session.getMaxInactiveInterval());
out.println("</BODY></HTML>");
}
}
Servlet Session Snoop
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
Integer count = (Integer)session.getAttribute("snoop.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("snoop.count", count);
out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
out.println("<BODY><H1>Session Snoop</H1>");
out.println("You"ve visited this page " + count +
((count.intValue() == 1) ? " time." : " times."));
out.println("<P>");
out.println("<H3>Here is your saved session data:</H3>");
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("<H3>Here are some vital stats on your session:</H3>");
out.println("Session id: " + session.getId() +
" <I>(keep it secret)</I><BR>");
out.println("New session: " + session.isNew() + "<BR>");
out.println("Timeout: " + session.getMaxInactiveInterval());
out.println("<I>(" + session.getMaxInactiveInterval() / 60 +
" minutes)</I><BR>");
out.println("Creation time: " + session.getCreationTime());
out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
out.println("Last access time: " + session.getLastAccessedTime());
out.println("<I>(" + new Date(session.getLastAccessedTime()) +
")</I><BR>");
out.println("Requested session ID from cookie: " +
req.isRequestedSessionIdFromCookie() + "<BR>");
out.println("Requested session ID from URL: " +
req.isRequestedSessionIdFromURL() + "<BR>");
out.println("Requested session ID valid: " +
req.isRequestedSessionIdValid() + "<BR>");
out.println("<H3>Test URL Rewriting</H3>");
out.println("Click
== Session Events ==
<!-- start source code -->
<source lang="java">
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());
}
}
use the Servlet API to manage session information
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;
import javax.servlet.http.HttpSession;
public class Counter extends HttpServlet {
static final String COUNTER_KEY = "Counter.count";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
HttpSession session = req.getSession(true);
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
int count = 1;
Integer i = (Integer) session.getAttribute(COUNTER_KEY);
if (i != null) {
count = i.intValue() + 1;
}
session.setAttribute(COUNTER_KEY, new Integer(count));
out.println("<html>");
out.println("<head>");
out.println("<title>Session Counter</title>");
out.println("</head>");
out.println("<body>");
out.println("Your session ID is <b>" + session.getId());
out.println("</b> and you have hit this page <b>" + count
+ "</b> time(s) during this browser session");
out.println("<form method=GET action=\"" + req.getRequestURI() + "\">");
out.println("<input type=submit " + "value=\"Hit page again\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}