@Slf4j@ControllerAdvice(basePackages = "com.paw.response")public class ApiResponseBodyAdvice implements ResponseBodyAdvice {
@Override public boolean supports (MethodParameter methodParameter, Class converterType) { // 可以过滤拦截哪些内容 比如方法类型 boolean supported = methodParameter.getMethod().getReturnType().equals(Result.class); return true; }
@Override public Object beforeBodyWrite (Object body, MethodParameter methodParameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { String path = request.getURI().getPath(); String klassMethod = methodParameter.getMethod().getDeclaringClass().getName() + "#" + methodParameter.getMethod().getName(); log.info("request uri: {} method: {}", path, klassMethod);
if(body instanceof String){ Result result = new Result(200,"success",body); return JSONUtil.toJsonStr(result); } if (!(body instanceof Result)) { return body; } Result result = (Result) body; // 通过Path匹配,或者header中的值 来过滤请求 AntPathMatcher pathMatcher = new AntPathMatcher(); boolean matched = pathMatcher.match("/api/newUri/**", path); log.info("path match {} {}", path, matched); if (matched) { // 重写返回码 result.setCode(newCode); } // 生成新的规范化转码 newCode // result.setCode(newCode);
return result; }
}
评论