使用自定義注解統一請求返回值
自定義一個注解,用於標記需要重寫返回值的方法/類
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?utm_medium=distribute.pc_category.none-task-blog-hot-5.nonecase&depth_1-utm_source=distribute.pc_category.none-task-blog-hot-5.nonecase