這篇文章主要介紹了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
以上是java 在Jetty9使用HttpSessionListener和Filter實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!