Home> Java> javaTutorial> body text

How to implement Java filters and interceptors?

WBOY
Release: 2023-05-10 08:10:12
forward
1279 people have browsed it

1. Similarities between filters and interceptors

1. Interceptors and filters both embody the idea of AOP. By enhancing the method implementation, both can intercept the request method.

2. Both interceptors and filters can set the execution order through the Order annotation

2. The difference between filters and interceptors

In Java Web development, filters (Filter) and interceptor (Interceptor) are common components used to process between requests and responses. Their main differences are as follows:

  • The running location is different: the filter is a component running between the Web server and the Servlet container, which can intercept all requests and responses in and out of the container; and intercept The controller intercepts and processes specific controller methods and is only executed within the controller.

  • The execution order is different: the execution order of filters is determined by the order in which they are declared in the web.xml file, and they are executed in the order of declaration; while the execution order of interceptors is It is determined according to the order of declaration in the configuration file, which means that the interceptor can specify the order.

  • Different functions: filters are mainly used to preprocess and filter requests, such as setting character sets, login verification, logging, etc.; while interceptors are mainly used to process requests Perform process control, such as permission verification, parameter injection, exception handling, etc.

  • The dependency framework is different: the filter is implemented based on the Servlet specification and does not depend on any specific framework; while the interceptor is usually implemented for a specific framework or library, such as Spring MVC Interceptors in the framework.

To sum up, filters and interceptors have certain differences in implementation methods, functions and usage scenarios. Developers can choose appropriate components according to specific needs.

3. Implementation of filters and interceptors

  • Configure the web layer in filter web.xml

In Java Web development, filters are mainly used to preprocess and filter requests. You can create a custom filter by implementing the javax.servlet.Filter interface. The specific steps are as follows:

Create a Java class, implement the javax.servlet.Filter interface, and implement the doFilter() method.

javaCopy code public class MyFilter implements Filter { public void init(FilterConfig config) throws ServletException { // Filter initialization operation}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 过滤器处理逻辑 // 对request和response进行预处理 // 调用chain.doFilter()方法,将请求传递给下一个过滤器或Servlet chain.doFilter(request, response); // 对response进行后处理 } public void destroy() { // 过滤器销毁操作 }
Copy after login
  • In the web.xml file Declare the filter and specify the URL pattern.

  • xmlCopy code myFilter com.example.MyFilter myFilter /*

In the above code, filter-name specifies the name of the filter, filter-class specifies the implementation class of the filter; filter-mapping specifies the URL pattern to be intercepted by the filter, /* means intercepting all requests.

  • Re-deploy the web application and start the server to use this filter to preprocess and filter requests.

It should be noted that when implementing a filter, you can obtain initialization parameters, ServletContext and other information through the FilterConfig object to achieve more refined filtering. At the same time, in the doFilter() method, the doFilter() method of the FilterChain object needs to be called to pass the request to the next filter or Servlet, otherwise the request will be blocked and cannot be processed normally.

  • Configure the action layer in interceptor springmvc.xml (between sevlet and controller)

In Java Web development , the interceptor (Interceptor) is a component used to intercept and process requests. You can create a custom interceptor by implementing the HandlerInterceptor interface. The specific steps are as follows:

Create a Java class, implement the HandlerInterceptor interface, and rewrite its three methods: preHandle(), postHandle() and afterCompletion().

javaCopy code public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Called before the controller method is executed, returning true means continuing to execute subsequent interceptors and Controller method; returning false means stopping execution of subsequent interceptors and controller methods. return true; }

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 在控制器方法执行之后、视图渲染之前被调用,可以对模型数据进行修改或查看。 } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 整个请求完成之后被调用,可以用于清理资源等工作。 }
Copy after login
  • Declare the interceptor in the Spring MVC configuration file and specify the interception path.

  • xmlCopy code mvc:interceptors

In the above XML configuration, MyInterceptor is a custom interceptor class name. By registering the interceptor in the Spring MVC configuration file, all requests passing through the interception path of the interceptor will be intercepted and processed accordingly.

It should be noted that when implementing an interceptor, you can choose which methods need to be rewritten according to your own needs to achieve refined interception processing. At the same time, in the preHandle() method, a boolean type result needs to be returned to indicate whether to continue executing subsequent interceptor and controller methods. If false is returned, the request will be stopped and execution will not continue.

4. Interview questions related to filters and interceptors

1. What is the difference between filters and interceptors?

Filter is a component used to preprocess and filter requests in the Servlet container. It can implement filtering, verification, compression and other functions. The interceptor (Interceptor) is a component used to intercept and process requests in the Spring MVC framework. It can implement functions such as permission verification, logging, and exception handling. Filters are executed in the Servlet container, while interceptors are executed in the Spring MVC framework.

2. What is the execution order of filters and interceptors?

In Java web applications, the execution order of filters and interceptors is determined by the order in which they are declared in the configuration file. Generally speaking, the filter or interceptor declared first will be executed first, and the filter or interceptor declared later will be executed later.

3. What are the functions of filters and interceptors?

Both filters and interceptors can process and control requests and implement a series of functions, such as request filtering, authentication, data encryption, logging, etc. Filters are mainly used to preprocess and filter requests, while interceptors are mainly used to intercept and process requests before or after the controller method is executed.

4. What are the usage scenarios of filters and interceptors?

Both filters and interceptors can be used to implement a series of control and management functions. For example, filters can be used in scenarios such as identity authentication, data encryption and decryption, request filtering and compression; while interceptors can be used in scenarios such as permission verification, logging, and exception handling.

5. How to use filters and interceptors in Java web applications?

In Java web applications, to use filters and interceptors, they need to be declared and registered in the configuration file. For filters, this can be done by adding the and tags in the web.xml file; for interceptors, it can be done by adding the mvc:interceptors tag in the Spring MVC configuration file. At the same time, when declaring and registering filters and interceptors, you also need to specify their execution order and interception path and other related information.

The above is the detailed content of How to implement Java filters and interceptors?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!