【发布时间】: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