AOP-- Oriented Programming. In the process of object-oriented programming, we can easily through inheritance, polymorphism to solve scale up. But for lateral features, such as uniform or unified logging encryption rule checking functions, object-oriented can not be solved. So we need to use AOP-- way Oriented Programming supplement. Filter and interceptors are all embodied aspect-oriented programming.
1, Filter Servlet container is dependent on, part of the Servlet specification, and the interceptor is independent existence, may be used in any case.
2, is completed by the execution Filter callback Servlet container, the interceptor is typically performed by a dynamic proxy.
3, Filter Servlet container life cycle managed by the interceptor can be managed by IoC container, it is possible to obtain by other examples Bean injection, etc., and therefore will be more convenient to use.
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class LogRecordFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
filterChain.doFilter(servletRequest,servletResponse);
// TODO Logging section
System.out.println (httpServletRequest.getRequestURL () + "; Request Processed cost =" + (System.currentTimeMillis () - start));
}
@Override
public void destroy() {
}
}
This class must inherit Filter class, this is the Servlet specification, this is no difference with the previous Web project. However, later with the filter class, the previous web project can be configured in web.xml, but the project did not spring boot the web.xml file, how to configure?
In Spring boot, there are two ways
1, FilterRegistrationBean need to complete the configuration. Which process is as follows:
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LogRecordFilter());
registration.addUrlPatterns("/*");
registration.setName("LogRecordFilter");
registration.setOrder(1);
return registration;
}
}
Configuration is complete, you need to configure the options include instantiating Filter class, and then specify the url of the match mode, set the filter name and the execution order, and this process configuration in web.xml in fact no difference, just different forms
2, WebFilter comment
@WebFilter(urlPatterns = "/*", filterName = "logRecordFilter ")
public class LogRecordFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
filterChain.doFilter(servletRequest, servletResponse);
System.out.println(httpServletRequest.getRequestURL() + ";Execute cost=" + (System.currentTimeMillis() - start));
}
@Override
public void destroy() {
}
}
Can be configured with @WebFilter, likewise, you may be provided url matching mode, the filter names. It should be noted that it is important @WebFilter this annotation is Servlet3.0 the norm, not the Spring boot provided. In addition to this comment, we still need to add another comment in the configuration class: @ServletComponetScan, specify the scan package.
@SpringBootApplication
@ServletComponentScan("com.xxxx.xxx.filters")
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
The second Filter does not specify the order of execution, but before the first implementation of a Filter. This annotation @WebFilter attribute does not specify the execution order, the execution order which depends on the name Filter is (note that the name is not arranged filter) Filter according to the class name in alphabetical order reverse order, and the specified filter @WebFilter priority FilterRegistrationBean higher than the filter configuration.
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogReocrdInterceptor implements HandlerInterceptor {
long start = System.currentTimeMillis();
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
start = System.currentTimeMillis();
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor cost="+(System.currentTimeMillis()-start));
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
HandlerInterceptor need to implement this interface, which consists of three methods:
In addition to implementing the above interface, we need to configure
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogRecordInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
Inheritance WebMVCConfigurerAdapter, rewritten addInterceptors this method to configure the interceptor, the configuration item on the main two, one is designated interceptor, the second is designated to intercept URL
By intercepting and filters can achieve the same functionality. However, the filter preHandle and postHandle are two methods, so had to start to set up a shared variable to store the start values, but this will be the presence of thread-safety issues. Of course, we can be resolved by other means, for example, can be a good solution to this problem through ThreadLocal.
By this point you can see, although the interceptor filter is better than in many scenes, but in this scenario, the filter to implement than the interceptor easier.
Interceptors and filters Some reprinted fromSpring Boot uses filter Filter - Jianshu Filters are filtering and preprocessing processes for data. When we visit the website, we sometimes publish some se...
Spring boot interceptor interceptor is executed in the servlet, Shiro should be Filter, execute before servlet. Springmvc interceptor is a priority below Shiro, Shiro is a Filter that is customized fo...
Filter There are two ways to create a Filter in Sping Boot. Method 1: Method 2: Mode 2 eventually generates the bean:FilterRegistrationBean Execution order order problem: use"Mode 2In the case of...
Foreword I believe that the small partners who are doing web will often come into contact with the three major Java devices (interceptors, filters, and listeners). When I recently sorted out, I found ...
table of Contents Application scenario Environmental preparation filter Listener Interceptor Link description operation result Filter and interceptor comparison Application scenario In the development...
Spring Boot adds filtering Method 1: Annotation Method 2: Register the Bean with the FilterRegistrationBean Spring Boot adds Filter in two ways: annotating and registering beans using the FilterRegist...
spring boot 2 servlet listenerfilter interceptor Generally for web development, using the controller can meet most of the needs, but sometimes the servlet listener filter and interceptor are al...
original: 1. Filter: Create ServletFilter.java to implement the Filter method test: Console output: 2. Listener: Create ContextListener.java class When the project starts, the listener is initialized ...
2019 Unicorn Enterprise Heavy Recruitment Standards for Python Engineers >>> 1 Listeners, filters and interceptors 1.1 Listener Listener, it is a server-side program that implements the javax...
When using Spring-Boot, embedded servlet containers register all listeners (such as HttpSessionListener listeners) that servlet, Filter, and Servlet specification by scanning. Spring boot's main servl...