Session在存储安全性要求较高的会话信息方面是必不可少的,Session当然绝对不是用来存储用户登录状态的,但类似验证码等敏感信息却必须存储在Session中。对于分布式Web应用自定义Session支持独立的状态服务器或集群是必须的。
ASP.NET通过SessionStateModule通过配置文件配置实际的Session提供程序,Session提供程序实现了SessionStateStoreProviderBase,因此在ASP.NET中实现自定义Session是通过继承SessionStateStoreProviderBase实现,配置Session是通过Web.config。ASP.NET自定义session的代码参考github上的开源项目SQLiteSessionStateStore。
同理,Java Servlet中使用自定义Session通过Filter可以实现。由于不同的servlet容器对Session的实现不同,所以通用性最好的方式是继承HttpServletRequestWrapper重写getSession方法返回自定义的Session对象。Filter采用了职责链模式(chain of responsibility),HttpServletRequestWrapper采用了装饰模式(Decorator),可以通过《Head First 设计模式》阅读模式的相关内容。
(1)首先自定义继承HttpSession的MySession(为了便于演示,仅包装了容器的session并转发调用)。
import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; public class MySession implements HttpSession { private HttpSession _containerSession; public MySession(HttpSession session) { this._containerSession = session; } @Override public long getCreationTime() { return this._containerSession.getCreationTime(); } @Override public String getId() { return this._containerSession.getId(); } @Override public long getLastAccessedTime() { return this._containerSession.getLastAccessedTime(); } @Override public ServletContext getServletContext() { return this._containerSession.getServletContext(); } @Override public void setMaxInactiveInterval(int interval) { this._containerSession.setMaxInactiveInterval(interval); } @Override public int getMaxInactiveInterval() { return this._containerSession.getMaxInactiveInterval(); } @SuppressWarnings("deprecation") @Override public HttpSessionContext getSessionContext() { return this._containerSession.getSessionContext(); } @Override public Object getAttribute(String name) { return this._containerSession.getAttribute(name); } @SuppressWarnings("deprecation") @Override public Object getValue(String name) { return this._containerSession.getValue(name); } @Override public Enumeration<String> getAttributeNames() { return this._containerSession.getAttributeNames(); } @SuppressWarnings("deprecation") @Override public String[] getValueNames() { return this._containerSession.getValueNames(); } @Override public void setAttribute(String name, Object value) { this._containerSession.setAttribute(name, value); } @SuppressWarnings("deprecation") @Override public void putValue(String name, Object value) { this._containerSession.putValue(name, value); } @Override public void removeAttribute(String name) { this._containerSession.removeAttribute(name); } @SuppressWarnings("deprecation") @Override public void removeValue(String name) { this._containerSession.removeValue(name); } @Override public void invalidate() { this._containerSession.invalidate(); } @Override public boolean isNew() { return this._containerSession.isNew(); } }
View Code(2)自定义继承HttpServletRequestWrapper的MyRequest