1.Web项目Session什么时候天生

须要明确一点,访问html文件的时候是不会天生Session的,Session的天生必须调用request.getSession或者request.getSession(true),request.getSession(false)不会天生Session。
JSP文件中默认自动添加<%@ page session=\"大众true\"大众>表示天生Session,jsp文件实在末了也是天生了Servlet类,添加了前面的配置后也会在Servlet类中调用request.getSession(true)。

如果单独的jsp页面不想天生Session可以在文件开头加入<%@ page session=\"大众false\公众>。
但是有些时候我们全体项目都不须要tomcat管理Session,如果每一个JSP,没一个Servlet都手动添加
<%@ page session=\"大众false\公众>和request.getSession(false)是不是有点太麻烦了?

在jsp页面怎么把session清空关于Tomcat若何禁用Session 的商量 HTML

2.如何不天生Session

先来借鉴下Shiro是如何自己管理Session 的,Shiro框架在管理权限时,用户的Session是通过框架来管理的。

须要认证的资源被访问时Shiro会判断Session。
在集成了Shiro框架的web项目中,对getSession方法debug下去创造,原来Shiro重写了getSession来实现Session的管理。
下面是Shiro覆盖的源码

publi class ShiroHttpServletRequest extends HttpServletRequestWrapper {\r……\rpublic HttpSession getSession(boolean create) {\r\r HttpSession httpSession;\r\r if (isHttpSessions) { //默认session\r httpSession = super.getSession(false); \r if (httpSession == null && create) {\r //Shiro 1.2: assert that creation is enabled (SHIRO-266):\r if (WebUtils._isSessionCreationEnabled(this)) {\r httpSession = super.getSession(create);\r } else {\r throw newNoSessionCreationException;\r }\r }\r } else {//Shiro管理的Session\r if (this.session == null) {\r\r boolean existing = getSubject.getSession(false) != null;\r\r Session shiroSession = getSubject.getSession(create);\r if (shiroSession != null) {\r this.session = new ShiroHttpSession(shiroSession, this, this.servletContext);\r if (!existing) {\r setAttribute(REFERENCED_SESSION_IS_NEW, Boolean.TRUE);\r }\r }\r }\r httpSession = this.session;\r }\r\r return httpSession;\r }\r public HttpSession getSession {\r return getSession(true);\r }\r……\r}

从上面Shiro源码可以看到原来Shiro重写了默认的HttpServletRequestWrapper类。

3.自己重写HttpServletRequestWrapper.getSession

我们也可以模拟Shiro的思路

//1.继续HttpServletRequestWrapper 重写getSession方法\rpublic class MyHttpServletRequest extends HttpServletRequestWrapper{\r...\r}\r\r//2.配置一个过滤器,在过滤器中配置自己的Request类\r @Override\r public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {\r chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);\r }

上面的管理方法对付Session 的管理变的非常灵巧,完备可以按照项目的需求连续拓展,比如Session的分布式管理,把Session数据缓存管理;移动端APP的Session管理等。