会话结束:
浏览器关闭;
主动关闭;
会话超时;
会话的底层实现方法:
cookies;
URL重写;
Example:
DemoSessionServlet.java
代码:
import java.io.IOException;
import java.io.PrintWriter;import java.sql.Date;import java.util.Enumeration;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 DemoSessionServlet extends HttpServlet {
private static final long serialVersionUID = 3144436730239445373L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response); }public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(); Integer counter = (Integer) session.getAttribute("counter"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); session.setMaxInactiveInterval(3600);response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>session demo servlet</title></head>"); out.println("<body>"); out.println("<h1>使用session的演示</h1>"); out.println("你已经访问了" + counter + "次.<br><br>"); if (session.isNew()) { out.println("这是一个新建的Session.<br><br>"); } else { out.println("这不是一个新建的Session.<br><br>"); } out.println("jsessionid: " + session.getId() + "<br><br>"); out.println("LastAccessedTime: " + session.getLastAccessedTime() + "<br>"); out.println("格式转换以后的LastAccessedTime: " + new Date(session.getLastAccessedTime()) + "<br><br>"); out.println("CreationTime: " + session.getCreationTime() + "<br>"); out.println("格式转换以后的CreationTime: " + new Date(session.getCreationTime()) + "<br><br>"); out.println("MaxInactiveInterval: " + session.getMaxInactiveInterval() + "秒<br>"); out.println("<br>使用Session对象的getAttributeNames<br>"); Enumeration enumer = session.getAttributeNames(); String name = null; while (enumer.hasMoreElements()) { name = (String) enumer.nextElement(); out.println("Session name:" + name + "<br>"); out.println("Session value:" + session.getAttribute(name) + "<br>"); } // session.removeAttribute("counter");//移除或者注销session
// session.invalidate(); out.println("</body>"); out.println("</html>"); out.flush(); out.close(); }}