nPolicy.RUNTIME)
@Documented
public @interface AutoResult {
boolean value() default true;
}
public class AutoResultReturnValueHandler implements HandlerMethodReturnValueHandler {
private static final IEventLogger logger = Logtube.getLogger(AutoResultReturnValueHandler.class.getName());
public AutoResultReturnValueHandler() {
}
public boolean supportsReturnType(MethodParameter returnType) {
return this.isRestController(returnType) && this.isAutoResult(returnType);
}
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
HttpServletRequest request = (HttpServletRequest)webRequest.getNativeRequest(HttpServletRequest.class);
mavContainer.setRequestHandled(true);
HttpServletResponse response = (HttpServletResponse)webRequest.getNativeResponse(HttpServletResponse.class);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
StringBuilder info = (StringBuilder)request.getAttribute("_REQUEST_LOG_INFO_");
if (info == null) {
info = new StringBuilder();
}
String requestId = (String)request.getAttribute("_REQUEST_ID_");
ResponseResult result = new ResponseResult();
result.setData(returnValue);
result.setErrorCode( ErrorCode.SUCCESS.getCode());
result.setErrorMsg(ErrorCode.SUCCESS.getMessage());
result.setRequestId(requestId);
String jsonString = JSON.toJSONString(result, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat});
Long startTime = (Long)request.getAttribute("_REQUEST_STARTTIME_");
info.append("[==响应结果=======]>: ").append(jsonString);
info.append("\n");
if (startTime != null) {
info.append("[==执行耗时=======]>: ").append(System.currentTimeMillis() - startTime).append("ms").append("\n");
}
logger.info(info.toString());
response.getWriter().append(jsonString);
}
private boolean isRestController(MethodParameter returnType) {
RestController annotation = (RestController)returnType.getDeclaringClass().getAnnotation(RestController.class);
return annotation != null;
}
private boolean isAutoResult(MethodParameter returnType) {
AutoResult methodAnnotation = (AutoResult)returnType.getMethodAnnotation(AutoResult.class);
if (methodAnnotation != null) {
return methodAnnotation.value();
} else {
AutoResult annotation = (AutoResult)returnType.getDeclaringClass().getAnnotation(AutoResult.class);
return annotation != null && annotation.value();
}
}
}
// 该类下的所有方法都会被拦截
@AutoResult
@RestController
@RequestMapping("/stock/depotinventorybalance")
public class DepotInventoryBalanceController {
@RequestMapping(value = "findById", method = RequestMethod.POST)
public DepotInventoryBalanceDto findById(@RequestBody DepotInventoryBalanceDto depotInventoryBalance) {
return this.depotInventoryBalanceService.findById(depotInventoryBalance);
}
// 导出的方法,最后是已文件流的方式返回,
// 不使用AutoResult返回的结果形式,即不使用自定义Handler类
@AutoResult(value = false)
public void export() {
depotInventoryBalanceService.export();
}
}
|