拦截器
拦截器分同步拦截器和异步拦截器;
HandlerInterceptor
方法和执行时机
可以看DispathcerServlet的原来确定它的三个方法的执行时机;
AsynHandlerInterceptor
看注释,主要用来清理在并发环境加清理ThreadLocal的数据;
ResponseBodyAdvice
对返回值备注了@ResponseBody或者返回ResponseEntity做了一些加工;
会在使用消息转换器转换为json数据之前进行数据转换输出;
package com.springbootpractice.interceptor.config; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.springbootpractice.interceptor.config.interceptor.MyInterceptor; import lombok.SneakyThrows; import org.springframework.context.annotation.Configuration; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import java.util.HashMap; import java.util.Map; /** * 说明:配置拦截器和设置统一返回格式 * @author carter * 创建时间: 2020年02月19日 11:03 下午 **/ @Configuration @ControllerAdvice public class WebConfig implements WebMvcConfigurer, ResponseBodyAdvice { @Override public void addInterceptors(InterceptorRegistry registry) { HandlerInterceptor myIntercepter = new MyInterceptor() ; registry.addInterceptor(myIntercepter).addPathPatterns("/**"); } @Override public boolean supports(MethodParameter returnType, Class converterType) { return true; } @SneakyThrows @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Map<String,Object> map = new HashMap(); map.put("result","true"); map.put("data",body); return new ObjectMapper().writeValueAsString(map); } }
小结
通过本小节,你可以学到:
- 如何配置拦截器,打印每个http接口的耗时;
- 如何设置接口的统一返回格式;
原创不易,转载请注明出处。
来源:https://www.cnblogs.com/snidget/p/12333933.html