springboot注册拦截器与返回统一标准响应格式

响应对象ResultVO

package com.example.poi.utils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @Author xu
 * @create 2023/7/5 01
 * @Version: V1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "响应对象")
public class ResultVO<T> implements Serializable {

    private static final long serialVersionUID = -2548645345465031121L;

    @ApiModelProperty(value = "状态码")
    private Integer code;

    @ApiModelProperty(value = "消息")
    private String message;

    @ApiModelProperty(value = "数据")
    private T data;

    public static <T> ResultVO success(T data){
        ResultVO resultVO = new ResultVO(HttpOperateCodeEnum.SUCCESS.getCode(), HttpOperateCodeEnum.SUCCESS.getMessage(), data);
        return resultVO;
    }

    public static <T> ResultVO<T> fail() {
        return new ResultVO<T>(HttpOperateCodeEnum.FAIL.getCode(), HttpOperateCodeEnum.FAIL.getMessage(), null);
    }

}

响应状态码HttpOperateCodeEnum

package com.example.poi.utils;


import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @Author xu
 * @create 2023/7/5 01
 * @Version: V1.0
 */
@Getter
@AllArgsConstructor
public enum HttpOperateCodeEnum {
    SUCCESS(200, "操作成功"),
    FAIL(400, "操作失败");

    private Integer code;

    private String message;

}


定义注解ResponseResultAnnotation

package com.example.poi.utils;


import java.lang.annotation.*;

/**
 * @Author xu
 * @create 2023/7/5 01
 * @Version: V1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface ResponseResultAnnotation {

}


响应加强实现类RestResponseHandler

package com.example.poi.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author xu
 * @create 2023/7/5 01
 * @Version: V1.0
 */
@RestControllerAdvice
public class RestResponseHandler implements ResponseBodyAdvice<Object> {
    public static final String Response_Result_Annotation = "Response_Result_Annotation";

    /**
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        ResponseResultAnnotation responseResultVO = (ResponseResultAnnotation) request.getAttribute(Response_Result_Annotation);
        return responseResultVO != null;
    }

    /**
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultVO) {
            return body;
        }
        return ResultVO.success(body);
    }
}


拦截器RestResponseInterceptor

package com.example.poi.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author xu
 * @create 2023/7/5 01
 */
public class RestResponseInterceptor implements HandlerInterceptor {
    public static final String Response_Result_Annotation = "Response_Result_Annotation";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(ResponseResultAnnotation.class)) {
                request.setAttribute(Response_Result_Annotation, clazz.getAnnotation(ResponseResultAnnotation.class));
            } else if (method.isAnnotationPresent(ResponseResultAnnotation.class)) {
                request.setAttribute(Response_Result_Annotation, method.getAnnotation(ResponseResultAnnotation.class));
            }
        }
        return true;
    }
}


将拦截器注册到Spring中管理

package com.example.poi.utils;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author xu
 * @create 2023/7/5 01
 * @Version: V1.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RestResponseInterceptor());
    }
}


你可能感兴趣的:(spring,boot,java,后端)