首页 > 开发 > Java > 正文

java 在Jetty9中使用HttpSessionListener和Filter

2024-07-13 10:09:07
字体:
来源:转载
供稿:网友

javascript/47129.html">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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表