赞
踩
前后分离时,我们要定义好统一的接口返回格式
eg:{“code”:0 ,“message”:“成功”,“data”:null}
返回格式与业务不相关且重复构建结果会产生大里冗余代码, 那么该怎么去抽离出来?
可以考虑将包含某些标记的方法或者类的结果进行重写,我们可以使用ResponseBodyAdvice来实现,当然也可作为加密解密的一种实现方式
@Target({ElementType.TYPE,ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface WebResponseResultAdvice {
}
@RequestMapping("/webResultAdvice")
@WebResponseResultAdvice
public Object testWebResult(String param) {
return demoService.testGlobalResult(param);
}
public class ResponseResultInterceptor extends HandlerInterceptorAdapter { private final static String WEB_RESULT_BUILD_TAG = "webResultBuildTag"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod)handler; //获取class Class<?> classType = handlerMethod.getBeanType(); //获取method Method method = handlerMethod.getMethod(); if (classType.isAnnotationPresent(WebResponseResultAdvice.class) || method.isAnnotationPresent(WebResponseResultAdvice.class)) { request.setAttribute(WEB_RESULT_BUILD_TAG,true); } } return true; } }
springboot可以统一配置在mvcconfig中
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptorRegistration = registry.addInterceptor(new ResponseResultInterceptor());
interceptorRegistration.addPathPatterns("/**");
}
}
@ControllerAdvice public class BaseWebResultHandler implements ResponseBodyAdvice { private final static String WEB_RESULT_BUILD_TAG = "webResultBuildTag"; @Override public boolean supports(MethodParameter methodParameter, Class aClass) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); Object attribute = request.getAttribute(WEB_RESULT_BUILD_TAG); return attribute == null ? false:true; } @Override public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { return JSON.toJSONString(WebResultDto.buildSuccessResult(o)); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。