0219 springmvc-攔截器和響應加強

攔截器

攔截器分同步攔截器和異步攔截器;java

HandlerInterceptor

方法和執行時機git

能夠看DispathcerServlet的原來肯定它的三個方法的執行時機;github

AsynHandlerInterceptor

看註釋,主要用來清理在併發環境加清理ThreadLocal的數據;web

ResponseBodyAdvice

對返回值備註了@ResponseBody或者返回ResponseEntity作了一些加工;spring

會在使用消息轉換器轉換爲json數據以前進行數據轉換輸出;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);
    }
}

小結

image.png

經過本小節,你能夠學到:springboot

  1. 如何配置攔截器,打印每一個http接口的耗時;
  2. 如何設置接口的統一返回格式;

image.png

代碼點我獲取!併發

原創不易,轉載請註明出處。mvc

相關文章
相關標籤/搜索