统一返回结果是说,不用在controller层,new一个对象,或用工厂创建这个对象,再返回这个对象,而是这个Action该返回什么就返回什么,
我们再通过mvc的流程,再对返回对象做进一步的封装,以达到我们的目的。
以下是controller层代码:我们返回一个list
@PostMapping("GetTask") public List<TaskResult> GetOpinionTaskHospitals(@RequestParam("month") Date month) { List<TaskResult> result = taskMgrService.GetTask(month, this.getCurrentUser());
return result;
}
通常的webapi的返回结果中都会有一个是否成功的标识,还有状态码,错误消息,还有返回结果对象,如下列的代码:
@Data public class AjaxResponse<T> { private Integer status; private String msg; private T data; }
最终返回的结果是这样的:
{ "status": 200, "msg": "", "data": [ { "id": null, "hospitalId": "1101", "hospitalName": "1101" }, { "id": null, "hospitalId": "1102", "hospitalName": "1102", }, { "id": null, "hospitalId": "1103", "hospitalName": "1103", "month": "201602" } ] }
具体实现的方法如下:
@Configuration public class RestReturnValueHandlerConfigurer implements InitializingBean { @Autowired private RequestMappingHandlerAdapter handlerAdapter; @Override public void afterPropertiesSet() throws Exception { List<HandlerMethodReturnValueHandler> list = handlerAdapter.getReturnValueHandlers(); List<HandlerMethodReturnValueHandler> newList = new ArrayList<>(); if (list != null) { for (HandlerMethodReturnValueHandler valueHandler: list) { if (valueHandler instanceof RequestResponseBodyMethodProcessor) { HandlerMethodReturnValueHandlerProxy proxy = new HandlerMethodReturnValueHandlerProxy(valueHandler); newList.add(proxy); } else { newList.add(valueHandler); } } } handlerAdapter.setReturnValueHandlers(newList); } }
public class HandlerMethodReturnValueHandlerProxy implements HandlerMethodReturnValueHandler { private HandlerMethodReturnValueHandler proxyObject; public HandlerMethodReturnValueHandlerProxy(HandlerMethodReturnValueHandler proxyObject) { this.proxyObject = proxyObject; } @Override public boolean supportsReturnType(MethodParameter returnType) { return proxyObject.supportsReturnType(returnType); } @Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { AjaxResponse response = new AjaxResponse(); response.setStatus(STATUS_CODE_SUCCEEDED); response.setMsg(""); response.setData(returnValue); proxyObject.handleReturnValue(response, returnType, mavContainer, webRequest); } private static final int STATUS_CODE_SUCCEEDED = 200; }
统一返回的结果与异常返回的结果是同一对象 ,请参考上一篇统一异常返回。