攔截器 攔截器分同步攔截器和非同步攔截器; HandlerInterceptor 方法和執行時機 可以看DispathcerServlet的原來確定它的三個方法的執行時機; AsynHandlerInterceptor 看註釋,主要用來清理在併發環境加清理ThreadLocal的數據; Respons ...
攔截器
攔截器分同步攔截器和非同步攔截器;
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介面的耗時;
- 如何設置介面的統一返回格式;
原創不易,轉載請註明出處。