java 在Jetty9中使用HttpSessionListener和Filter
投稿:lqh
这篇文章主要介绍了java 在Jetty9中使用HttpSessionListener和Filter的相关资料,需要的朋友可以参考下
java 在Jetty9中使用HttpSessionListener和Filter
HttpSessionListener
当Session创建或销毁的时候被调用
示例代码:
class MyHttpSessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { System.out.println("sessionCreated"); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { System.out.println("sessionDestroyed"); } }
注册方法:
ServletContextHandler.getSessionHandler().addEventListener(new MyHttpSessionListener());
注意: 若整个请求中都没有用到Session, 则不会生成它, 也不会调用Listener
Filter
当客户端请求数据时被调用
示例代码:
class MyFilter implements Filter { public MyFilter() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (servletRequest instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; System.out.println(httpRequest.getServletPath()); } filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
注册方法:
ServletContextHandler.addFilter(new FilterHolder(new MyFilter()), "/*", EnumSet.allOf(DispatcherType.class));
注意: 若请求的路径错误, 则不会触发Filter
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!