【问题标题】:Spring MVC / Rest - return standard responseSpring MVC / Rest - 返回标准响应
【发布时间】:2014-09-26 13:13:15
【问题描述】:

在 Spring MVC 中,我正在使用控制器编写一些东西,本质上是执行 REST 以及一些附加功能。

大部分功能都是从 ExtJS 调用到 spring 中的,为了遵守它们的约定,返回的总是一个 json 对象,格式如下:

{
    success: true,
    data: { ... }
}

或者在出错的情况下:

{
    success: false,
    message: { ... }
}

对于异常很容易 - Spring 提供了@ControllerAdvice 和@ExceptionHandler 等,以便可以将错误捕获在一个地方并且标准响应有效。

但是,有一种简单的方法可以强制以相同的方式传递所有有效响应,以便每次都可以发送成功元素,并将数据发送回数据对象中。换句话说,目前对于每个电话我都必须做类似

@RequestMapping(method = RequestMethod.POST)
    @ResponseBody

    public HashMap<String, Object> add(@RequestBody ManagedView targetTest) {
        ManagedView result = service.add(targetTest);
        HashMap<String, Object> ret = new HashMap<String, Object>();
        ret.put("success", new Boolean(true));
        ret.put("data", result);
        return ret;
    }

而我想做的是有类似的东西

@RequestMapping(method = RequestMethod.POST)    
    public ManagedView  add(@RequestBody ManagedView targetTest) {
        return service.add(targetTest);

    }
// and each response intercepted by something like this

    public HashMap<String, Object> addWrapper(Object result) {

        HashMap<String, Object> ret = new HashMap<String, Object>();
        ret.put("success", new Boolean(true));
        ret.put("data", result);
        return ret;
    }

我很感激我可以创建一个标准的实用程序类型函数来执行此操作,但是否有一些开箱即用的方法,无需我向所有方法添加相同的代码 - 最好是全局设置。

提前致谢

【问题讨论】:

标签: java spring spring-mvc extjs


【解决方案1】:

我认为你可以使用org.springframework.web.servlet.HandlerInterceptor

它包含preHandle()postHandle()afterCompletion() 方法。在您的情况下,您可以使用postHandle() 方法在将ModelAndView 对象渲染到查看页面之前对其进行操作,这将是所有控制器的共同点。

【讨论】:

    【解决方案2】:

    这是我刚刚使用的一个解决方案,我经历了几种方法,直到我找到了这个,这是我认为最简单的一个:

    @ControllerAdvice
    public class StandardResponseBodyWrapAdvice implements ResponseBodyAdvice<Object> {
        @Override
        public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
            return (AnnotationUtils.findAnnotation(returnType.getContainingClass(), ResponseBody.class) != null ||
                    returnType.getMethodAnnotation(ResponseBody.class) != null);
        }
    
        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
            ApiResponseDTO<Object> resp = new ApiResponseDTO<>();
            resp.setVersion("1.0");
            resp.setSuccess(true);
            resp.setData(body);
            return resp;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2022-01-23
      相关资源
      最近更新 更多