欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 在Jetty9中使用HttpSessionListener和Filter

程序员文章站 2023-12-13 20:49:16
java 在jetty9中使用httpsessionlistener和filter httpsessionlistener 当session创建或销毁的时候被调用...

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

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

上一篇:

下一篇: