Home  >  Article  >  Java  >  Detailed explanation of examples of filters, listeners, and interceptors in Java

Detailed explanation of examples of filters, listeners, and interceptors in Java

零下一度
零下一度Original
2017-06-25 13:32:382473browse

1. Filter

Filter is also called filter. It is the most practical technology in Servlet technology. Web developers use Filter technology to manage all web resources managed by the web server: such as Jsp, Servlets, static image files or static html files are intercepted to achieve some special functions. For example, some advanced functions such as URL-level permission access control, sensitive vocabulary filtering, and response information compression can be implemented.

It is mainly used to preprocess user requests and can also postprocess HttpServletResponse. The complete process of using Filter: Filter preprocesses the user request, then hands the request to Servlet for processing and generates a response, and finally Filter post-processes the server response.

Generally used with spring architecture in the following places:

1.1 To deal with the encoding problem of character writing into the database, configure the code in web.xml

 1 <filter> 2       <filter-name>Encoding</filter-name> 3       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4       <init-param> 5           <param-name>encoding</param-name> 6           <param-value>utf-8</param-value> 7       </init-param> 8   </filter> 9   <filter-mapping>10       <filter-name>Encoding</filter-name>11       <url-pattern>/*</url-pattern>12   </filter-mapping>
View Code

1.2 Deal with the initialization sequential loading problem that occurs when integrating with mongodb, and use Filter to complete the proxy function

 1 <!-- 告诉ContextLoaderListener叫在spring的配置文档的位置--> 2   <context-param> 
 3      <param-name>contextConfigLocation</param-name> 
 4      <param-value> 
 5          classpath:spring-shiro-web.xml, 6           /WEB-INF/spring-servlet.xml 7      </param-value> 
 8  </context-param> 
 9 10 <filter>11     <filter-name>shiroFilter</filter-name>12     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>13     <init-param>14         <param-name>targetFilterLifecycle</param-name>15         <param-value>true</param-value>16     </init-param>17 </filter>18 <!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->19 <!-- requests.  Usually this filter mapping is defined first (before all others) to -->20 <!-- ensure that Shiro works in subsequent filters in the filter chain:             -->21 <filter-mapping>22     <filter-name>shiroFilter</filter-name>23     <url-pattern>/*</url-pattern>24 </filter-mapping>25 26 <!-- 在tomcat启动的时候优先加载spring的配置文档 -->27     <listener> 
28         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
29      </listener>
View Code
过滤器生命周期的四个阶段:
<span style="font-size: 14px">1、实例化:Web容器在部署Web应用程序时对所有过滤器进行实例化。Web容器回调它的无参构造方法。</span><br><span style="font-size: 14px">2、初始化:实例化完成之后,马上进行初始化工作。Web容器回调init()方法。</span>
3、过滤:请求路径匹配过滤器的URL映射时。Web容器回调doFilter()方法——主要的工作方法。
4、销毁: Web容器在卸载Web应用程序前,Web容器回调destroy()方法。

 

二、监听器

监听器Listener就是在application,session,request三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。

Listener是Servlet的监听器,可以监听客户端的请求和服务端的操作等。

主要有以下三类:

1、ServletContext监听

ServletContextListener:用于对Servlet整个上下文进行监听(创建、销毁)。
ServletContextAttributeListener:对Servlet上下文属性的监听(增删改属性)。

2、Session监听

Session属于http协议下的内容,接口位于javax.servlet.http.*包下。

HttpSessionListener接口:对Session的整体状态的监听。
HttpSessionAttributeListener接口:对session的属性监听。
session的销毁有两种情况:

2.1 session超时,web.xml配置: <session-config> <session-timeout>120session-timeout>

session-config>   

2.2 手工使session失效 public void invalidate();//使session失效方法。session.invalidate();

3、Request监听

ServletRequestListener:用于对Request请求进行监听(创建、销毁)。
ServletRequestAttributeListener:对Request属性的监听(增删改属性)。

4、在web.xml中配置

Listener配置信息必须在Filter和Servlet配置之前,Listener的初始化(ServletContentListener初始化)比Servlet和Filter都优先,

而销毁比Servlet和Filter都慢。

<listener> <listener-class>com.listener.classlistener-class> listener>

<context-param> <param-name>contextConfigLocationparam-name>

<param-value>classpath:spring/applicationContext-*.xmlparam-value>

context-param>

#< listener>

##  <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

#listener># 4. 1 Spring uses IntrospectorCleanupListener to clean the cacheThe function of this listener is to refresh the Introspector cache of JDK's JavaBeans when the web application is closed to ensure that the class loader of the web application and the classes it loads are released correctly resource. If the JavaBeans Introspector has been used to analyze application classes, the system-level Introspector cache will hold a hard reference to these classes. Therefore, these classes and the web application's class loader will not be reclaimed by the garbage collector when the web application is closed! The IntrospectorCleanupListener will clean it appropriately so that it can be recycled by the garbage collector.

The only way to clean up the Introspector is to flush the entire Introspector cache, there is no other way to specify the exact class that the application is referencing. This will delete the cached Introspector results from all other applications on the server.

When using Spring's internal bean mechanism, there is no need to use this listener, because Spring's own introspection results cache will immediately refresh the analyzed JavaBeans Introspector cache, and will only refresh the analyzed JavaBeans Introspector cache in the application's own ClassLoader There is a cache inside. Although Spring itself does not generate leaks, note that even in cases where the Spring framework classes themselves reside in a "common" class loader (such as the system's ClassLoader), the IntrospectorCleanupListener should still be used. In this case, this IntrospectorCleanupListener will properly clean up Spring's introspection cache.

Application classes rarely need to use JavaBeans Introspector directly, so it is usually not the Introspector resource that causes memory leaks. In contrast, many libraries and frameworks, such as Struts and Quartz, do not clean the Introspector.

It should be noted that a simple Introspector leak will cause the class loader of the entire Web application to not be recycled! The result of this will be that when the web application is closed, all the static class resources (such as single instance objects) of the application will not be released. The root cause of memory leaks is not actually these unrecycled classes!

Note: IntrospectorCleanupListener should be registered as the first Listener in web.xml, before any other Listener, such as before Spring's ContextLoaderListener, to ensure that the IntrospectorCleanupListener takes effect at the appropriate time in the web application's life cycle.

<listener>

##  <listener-class>org.springframework.web.util.IntrospectorCleanupListener

listener-class>

#listener>

# 3. spring interceptor

#spring managed interceptors need to inherit##Intercepter implements HandlerInterceptor

##To enter the interceptor, you first need to configure the spring entrance ##  spring org.springframework.web.servlet.DispatcherServlet

 spring

/


The above writing method will not filter out urls ending in .jsp , If you need to process .jsp, you need to use it with a filter, or use the shiro architecture

But we don’t need to filter and intercept general static resources, you can use the following configuration

web.xml configuration

  default

  *.css

  *.js

/image/*


spring-servlet .xml configuration, pay attention to the addition of the header file


The above is the detailed content of Detailed explanation of examples of filters, listeners, and interceptors in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn