java 在Jetty9中使用HttpSessionListener和Filter

时间:2021-12-14 07:25:05

javaJetty9中使用HttpSessionListener和Filter

HttpSessionListener

当Session创建或销毁的时候被调用

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
class MyHttpSessionListener implements HttpSessionListener {
  @Override
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    System.out.println("sessionCreated");
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    System.out.println("sessionDestroyed");
  }
}

注册方法:

?
1
ServletContextHandler.getSessionHandler().addEventListener(new MyHttpSessionListener());

注意:  若整个请求中都没有用到Session, 则不会生成它, 也不会调用Listener

Filter

当客户端请求数据时被调用

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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() {
 
  }
}

注册方法:

?
1
ServletContextHandler.addFilter(new FilterHolder(new MyFilter()), "/*", EnumSet.allOf(DispatcherType.class));

注意: 若请求的路径错误, 则不会触发Filter

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

原文链接:http://blog.csdn.net/sidyhe/article/details/52084558