The difference between filters, listeners, and interceptors

1. Filter

The filter in servlet is a server-side program that implements the javax.servlet.Filter interface. The main purpose is to filter character encoding and make some business logic judgments. The working principle is that as long as you configure the client request to be intercepted in the web.xml file, it will help you intercept the request. At this time, you can uniformly set the encoding for the request or response (Request, Response) to simplify the operation; At the same time, it can also make logical judgments, such as whether the user has logged in, whether he has permission to access the page, and so on. It is started with the startup of your web application. It is only initialized once, and related requests can be intercepted in the future. It will only be destroyed when your web application is stopped or redeployed. The following is an example of filtering and coded code to understand its use. :

 

 

[c-sharp]  view plain copy  
 
  1.  MyCharsetFilter.java encoding filter   
  2. package ...;   
  3. import ...;   
  4. // Main purpose: filter character encoding; secondly, do some application logic judgment, etc.   
  5. // Filter starts with the web application   
  6. // When the web application is restarted or destroyed, the Filter is also destroyed   
  7. public class MyCharsetFilter implements Filter {   
  8.      private FilterConfig config = null;   
  9.      public void destroy() {   
  10. System.out.println ( "          MyCharsetFilter is ready to destroy...");   
  11.      }   
  12.     
  13.      public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {   
  14.          // forced type conversion   
  15.          HttpServletRequest request = (HttpServletRequest)arg0;   
  16.          HttpServletResponse response = (HttpServletResponse)arg1;   
  17.          // Get the encoding set set by web.xm and set it to Request and Response request.setCharacterEncoding(config.getInitParameter("charset")); response.setContentType(config.getInitParameter("contentType")); response.setCharacterEncoding(config .getInitParameter("charset"));            
  18.         // forward the request to the destination   
  19.          chain.doFilter(request, response);   
  20.      }   
  21.     
  22.      public void init(FilterConfig arg0) throws ServletException {   
  23.          this.config = arg0;   
  24. System.out.println ( "          MyCharsetFilter initialization...");   
  25.      }   
  26.  }   

 

 

The following is MyCharsetFilter.java configured in web.xml: 

 

[c-sharp]  view plain copy  
 
  1. <filter>   
  2.       <filter-name>filter</filter-name>   
  3.       <filter-class>dc.gz.filters.MyCharsetFilter</filter-class>   
  4.       <init-param>   
  5.           <param-name>charset</param-name>   
  6.           <param-value>UTF-8</param-value>   
  7.       </init-param>   
  8.       <init-param>   
  9.           <param-name>contentType</param-name>   
  10.           <param-value>text/html;charset=UTF-8</param-value>   
  11.       </init-param>   
  12.   </filter>   
  13.   <filter-mapping>   
  14.       <filter-name>filter</filter-name>   
  15.       <!-- * Represents intercepting all requests or specifying requests /test.do /xxx.do -->   
  16.       <url-pattern>/*</url-pattern>   
  17.   </filter-mapping>   

 

 

     The above examples briefly illustrate the use of Filter, and other specific applications can be seen in specific scenarios. 

2. Listener

Now let's talk about Servlet's Listener, which is a server-side program that implements the javax.servlet.ServletContextListener interface. It is also started when the web application is started, initialized only once, and destroyed when the web application stops. The main functions are: Do some initialization content addition work, set some basic content, such as some parameters or some fixed objects and so on. The following uses the listener to initialize the database connection pool DataSource to demonstrate its use: 

 

[c-sharp]  view plain copy  
 
  1. MyServletContextListener.java   
  2.  package dc.gz.listeners;   
  3.  import javax.servlet.ServletContext;   
  4.  import javax.servlet.ServletContextEvent;   
  5.  import javax.servlet.ServletContextListener;   
  6.  import org.apache.commons.dbcp.BasicDataSource;   
  7.     
  8.   /**  
  9.   * Web application listener  
  10.   */   
  11.  public class MyServletContextListener implements ServletContextListener {     
  12.      // Destruction method of application listener   
  13.      public void contextDestroyed(ServletContextEvent event) {   
  14.          ServletContext sc = event.getServletContext();   
  15.          // Called before the entire web application is destroyed to clear all the content set in the application space   
  16.          sc.removeAttribute("dataSource");   
  17.         System.out.println ( "Destruction work done...");   
  18.      }   
  19.     
  20.      // Initialize the application listener   
  21.      public void contextInitialized(ServletContextEvent event) {   
  22.          // Through this event, you can get the space of the entire application   
  23.          // Do some initialized content addition work when the entire web application is started   
  24.          ServletContext sc = event.getServletContext();   
  25.          // Set some basic content; such as some parameters or some fixed objects   
  26.          // Create a DataSource object, connection pooling technology dbcp   
  27.          BasicDataSource bds = new BasicDataSource();   
  28.          bds.setDriverClassName("com.mysql.jdbc.Driver");                       bds.setUrl("jdbc:mysql://localhost:3306/hibernate");   
  29.          bds.setUsername("root");   
  30.          bds.setPassword("root");   
  31.          bds.setMaxActive(10); //Maximum number of connections   
  32.          bds.setMaxIdle(5); //Maximum number of management   
  33.          //bds.setMaxWait(maxWait); maximum waiting time   
  34.          // Put the DataSource into the ServletContext space,   
  35.          // For use by the entire web application (get database connection)   
  36.          sc.setAttribute("dataSource", bds);   
  37.          System.out.println ( "Application listener initialization completed...");   
  38.          System.out.println ( "DataSource has been created...");   
  39.      }   
  40.  }   

 

 

The configuration in web.xml is as follows, which is very simple:

 

[c-sharp]  view plain copy  
 
  1. <!-- configure application listener -->   
  2.   <listener>   
  3.       <listener-class>dc.gz.listeners.MyServletContextListener</listener-class>   
  4.   </listener>   

 

 

After this configuration, the BasicDataSource object can be obtained through the ServletContext in the web application in the future, so as to obtain the connection to the database, improve performance, and facilitate use.

3. Interceptor

Interceptors are applied in aspect-oriented programming, which is to call a method before your service or a method, or call a method after the method. It is a reflection mechanism based on JAVA. The interceptor is not in web.xml, such as struts is configured in struts.xml,

 

[c-sharp]  view plain copy  
 
  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable  
  2. {  
  3. Object result = null;  
  4. System.out.println("before invoke method :" + method.getName());  
  5. result = method.invoke(this.targetObj, args);  
  6. System.out.println("after invoke method : " + method.getName());  
  7. return result;  
  8. }  

 

 

Summarize:

1. Filter: The so-called filter is used to filter as the name implies. In java web, the request and response you pass in filter out some information in advance, or set some parameters in advance, and then pass in the action of servlet or struts for business Logic, such as filtering out illegal urls (not the address request of login.do, if the user is not logged in), or uniformly setting the character set before the action of the incoming servlet or struts, or removing some illegal characters (chat rooms often used, some swear words). The filter process is linear. After the url is sent and checked, the original process can continue to be executed downwards and be received by the next filter, servlet, etc.

2. Listener: This thing is often used in the c/s mode, and it will generate a process for a specific event. Listening is used in many modes. For example, the observer mode is a monitor. Another example struts can be used to monitor to start. Servlet listeners are used to monitor the occurrence of some important events, and the listener object can do some necessary processing before and after the event occurs.

3. Java interceptors are mainly used in plug-ins, extensions such as hivernate spring struts2, etc. are somewhat similar to slicing-oriented technologies. Before using them, you must declare a paragraph in the configuration file, that is, the xml file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324974621&siteId=291194637