[Spring Boot]使用自定义注解统一请求返回值
程序员文章站
2022-06-20 12:24:57
使用自定义注解统一请求返回值自定义一个注解,用于标记需要重写返回值的方法/类package com.timee.annotation;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE, ElementType.METHOD})@Documentedpublic @interface ResponseData {}使用拦截器拦截所有请求创建拦截器pub...
使用自定义注解统一请求返回值
自定义一个注解,用于标记需要重写返回值的方法/类
package com.timee.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface ResponseData {
}
使用拦截器拦截所有请求
创建拦截器
public class ResponseInterceptor implements HandlerInterceptor {
public static final String RESPONSE_DATA_REWRITE = "RESPONSE_DATA_REWRITE";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
final HandlerMethod handlerMethod = (HandlerMethod) handler;
final Class<?> clazz = handlerMethod.getBeanType();
final Method method = handlerMethod.getMethod();
if (clazz.isAnnotationPresent(ResponseData.class)) {
request.setAttribute(RESPONSE_DATA_REWRITE, clazz.getAnnotation(ResponseData.class));
} else if (method.isAnnotationPresent(ResponseData.class)) {
request.setAttribute(RESPONSE_DATA_REWRITE, method.getAnnotation(ResponseData.class));
}
}
return true;
}
}
应用拦截器到项目
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ResponseInterceptor())
.addPathPatterns("/**");
}
}
重写返回值
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice {
public static final String RESPONSE_DATA_REWRITE = "RESPONSE_DATA_REWRITE";
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
return request.getAttribute(RESPONSE_DATA_REWRITE) == null ? false : true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
log.info("请求[{}]需要重写返回值格式", serverHttpRequest.getURI());
return "你好,世界!";
}
}
测试请求
@Controller
public class Controller {
@GetMapping("/test")
@ResponseBody
@ResponseData
public String test() {
return "Hello World!";
}
}
运行结果
本文地址:https://blog.csdn.net/snowiest/article/details/112102772