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
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!