java 在Jetty9中使用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