Filters and interceptors are common in web development. In layman’s terms, filters simply mean “get what you want” and ignore what you don’t want. Blockers can simply mean “deny what you want to deny” and care about what you want to deny, such as blocking sensitive words from a BBS forum.

Filters rely on the servlet container and are a JavaEE standard that preprocesses requests after they enter the container, before they enter the servlet, and post-processes them between the end of the request and its return to the front end. The implementation is based on function callbacks and can filter almost any request, but the disadvantage is that a filter instance can only be called once when the container is initialized. The purpose of using the filter is to do some filtering operations to obtain the data we want to obtain, such as: modify the character encoding in the filter; Modify some parameters of HttpServletRequest in the filter, including filtering vulgar text, dangerous characters, and so on

Interceptors in Java are objects that dynamically intercept Action calls. It provides a mechanism for developers to define code that executes before and after an action is executed, to prevent an action from executing before it is executed, and also provides a way to extract reusable parts of the action. In AOP (aspect-oriented Programming) interceptors are used to intercept a method or field before it is accessed and then add some action before or after it.

V Filter Demo

1.1 create MyTestFilter

package com.demo.Filter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * Created by toutou on 2018/10/27. */ @Slf4j @Component public class MyTestFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("1111111111111111111111111"); Log.info ("filter initialization "); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("2222222222222222222222222"); Log.info ("doFilter request processing "); // The link is directly passed to the next filter chain.dofilter (request, response); } @Override public void destroy() { System.out.println("33333333333333333333333333"); The info (" filter to destroy "); }}Copy the code

1.2 Viewing IDEA Startup Logs

1.3 Starting Tomcat and viewing logs

If you need to specify a path for the filter to work, refer to the WebConfig class.

V Interceptor Demo

2.1 MyTestInterceptor

package com.demo.Filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * Created by toutou on 2018/10/27. */ @Component public class MyTestInterceptor implements HandlerInterceptor { /* * */ @override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {} /* * Processing the request before completing the rear view rendering */ @override public void postHandle(HttpServletRequest) arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {} /* * Intercepting requests before entering the Controller layer */ @override public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { System.out.println("MyTestInterceptor 1111111111"); return true; }}Copy the code

2.2 WebConfig

package com.demo.Filter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Resource; /** * Created by toutou on 2018/10/27. */ @Configuration public class WebConfig implements WebMvcConfigurer { @Resource private MyTestInterceptor myTestInterceptor; Public void addInterceptors(InterceptorRegistry registry) {Override public void addInterceptors(InterceptorRegistry registry) { AddInterceptor (myTestInterceptor).addPathPatterns("/show"); } @Bean public FilterRegistrationBean testFilterRegistration(MyTestFilter myTestFilter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(myTestFilter); / / add filter registration. AddUrlPatterns ("/show "); / filter/set path, / * / / registration. All paths through the addInitParameter (" name ", "alue"); // add the default parameter registration.setName("MyFilter"); // Set priority registration.setOrder(1); // Set priority return registration; }}Copy the code

Operation effect:

V Precautions

Note that the scan path of the startup class is set.

package com.demo.hellospringboot; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.demo"}) @MapperScan(basePackages = {"com.demo.dao"}) @Slf4j public class HellospringbootApplication { public static void main(String[] args) { SpringApplication.run(HellospringbootApplication.class, args); }}Copy the code

V Source code address

Github.com/toutouge/ja…

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \