标签:tomcat session cookie 源码 cookies
在看本文之前,请先查阅相关Session与Cookie的资料。uml图如下:
StandardSession.java /** * The facade associated with this session. NOTE: This value is not * included in the serialized version of this object. */ private transient StandardSessionFacade facade = null;Catalina通过一个叫session管理器的组件来管理建立的Session对象,该组件由org.apache.catalina.Manager接口表示。Session管理器与一个Context级别的容器相关联。
Session管理器组件负责管理Session对象,例如创建和删除Session对象。在catalina中,ManagerBase是一个工具类,提供了最基本的一些功能。
// add a Manager Manager manager = new StandardManager(); context.setManager(manager);我们的servlet如下:
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 java.io.IOException; import java.io.PrintWriter; public class SessionServlet extends HttpServlet { private static final long serialVersionUID = -446310114281616885L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("SessionServlet -- service"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>SessionServlet</title></head>"); out.println("<body>"); String value = request.getParameter("value"); HttpSession session = request.getSession(true); out.println("<br>the previous value is " + (String) session.getAttribute("value")); out.println("<br>the current value is " + value); session.setAttribute("value", value); out.println("<br><hr>"); out.println("<form>"); out.println("New Value: <input name=value>"); out.println("<input type=submit>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } }编译好的servletclass文件放在什么地方,还用我说吗?如果不知道就先看看前面几章吧。
先上最终的结果图:
先输入33然后15最后57的效果图
parseHeaders方法下: if (name.equals("cookie")) { Cookie cookies[] = RequestUtil.parseCookieHeader(value); for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("jsessionid")) { // Override anything requested in the URL if (!request.isRequestedSessionIdFromCookie()) { // Accept only the first session id cookie request.setRequestedSessionId(cookies[i].getValue()); request.setRequestedSessionCookie(true); request.setRequestedSessionURL(false); } } request.addCookie(cookies[i]); } }第一次请求SessionServlet的时候,自然没有jsessionid,RequestedSessionId也为空,就要manager.createSession()
if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) session = null; if (session != null) { return (session.getSession()); } }
how tomcat works 读书笔记九 Session管理
标签:tomcat session cookie 源码 cookies
原文地址:http://blog.csdn.net/dlf123321/article/details/40980895