Principle :
(1) The interceptor implements related business before and after each request is processed , similar to the filter of Servlet . Let common beans implement the HandlerInterceptor interface or inherit the HandlerInterceptorAdapter class to implement custom interceptors.
(2) Create another class to register a custom interceptor by inheriting and rewriting the addInterceptors method of Web MvcConfigurerAdapter . The business meaning is the time of each processing. As long as the request is sent, it will first go through the interceptor
Several specific methods of WebMvcConfigurerAdapter:
/** Solve cross domain problems **/
public voidaddCorsMappings(CorsRegistry registry) ;
/** Add interceptor **/
voidaddInterceptors(InterceptorRegistry registry);
/** Configure the view resolver here **/
voidconfigureViewResolvers(ViewResolverRegistry registry);
example:
@Override
public voidconfigureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp");
registry.enableContentNegotiation(new MappingJackson2JsonView());
}
/** Configure some options for content moderation **/
This method is specifically used to configure some parameters of content moderation. This is relatively simple, let's see it directly through an example:
voidconfigureContentNegotiation(ContentNegotiationConfigure configure);
example:
publicvoid configureContentNegotiation(ContentNegotiationConfigure configure) {
/* Whether to determine the mediatype by requesting the extension of the Url */
configurer.favorPathExtension(true)
/* Do not check the Accept request header */
.ignoreAcceptHeader(true)
.parameterName("mediaType")
/* Set the default media yype */
.defaultContentType(MediaType.TEXT_HTML)
/* Requests ending in .html will be treated as MediaType.TEXT_HTML*/
.mediaType("html",MediaType.TEXT_HTML)
/* Requests ending in .json will be treated as MediaType.APPLICATION_JSON*/
.mediaType("json",MediaType.APPLICATION_JSON);
}
/** View Jump Controller **/
voidaddViewControllers(ViewControllerRegistry registry);
/** Static resource processing **/
voidaddResourceHandlers(ResourceHandlerRegistry registry);
/** Default static resource handler **/
voidconfigureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
For example: to implement a send a request to see the total time spent sending the request
code show as below:
package com.example.Spring.Boot1.Interceptor; import java.nio.charset.Charset; import java.util.List; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @RestController public class DemoInterceptorTest extends WebMvcConfigurerAdapter { /************Solve the problem of garbled characters********************************/ public HttpMessageConverter<String> responseBodyConverter() { StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8")); return converter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); converters.add(responseBodyConverter()); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } /********************Here is the call of the interceptor ********************/ public DemoInterceptor demoInterceptor() { return new DemoInterceptor(); } //register interceptor @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(demoInterceptor()); } }
// The specific interception does.
Override the preHandle class (this is executed before sending the request) and the postHandle class (this is executed after the sending is over)
package com.example.Spring.Boot1.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; //interceptor public class DemoInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("*******拦截器开始*******"); String title = request.getParameter("title"); String reader = request.getParameter("reader"); long time = System.currentTimeMillis();// 得到当前的时间 System.out.println(time); request.setAttribute("starttime", time); // 通过request存储 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startime = (long) request.getAttribute("starttime"); long endtime = System.currentTimeMillis(); System.out.println(startime + " " + endtime); request.removeAttribute("time"); request.removeAttribute("reader"); System.out.println("This time is: " + new Long(endtime - startime) + "ms"); } }Finally add an interface side request
package com.example.Spring.Boot1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) public class SpringBoot1Application { @RequestMapping("/aa") public String aa() { return "Test for the first time!!!"; } }
Finally enter the interface address: http://localhost:8011/aa
Every time the program is started, as long as the request is sent on the interface, it will first pass through the DemoInterceptor class, and then execute the execution process here .
Result: The following information is printed on the console interface
******Interceptor starts *******
15258435409081525843540908 1525843540931
This time is: 23ms