gpt4 book ai didi

java - Spring MVC/Rest - 返回标准响应

转载 作者:行者123 更新时间:2023-11-30 03:44:36 27 4
gpt4 key购买 nike

在 Spring MVC 中,我正在使用 Controller 编写一些东西,本质上是执行 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;
}

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

提前致谢

最佳答案

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

它包含 preHandle()postHandle()afterCompletion() 方法。在您的情况下,您可以使用 postHandle() 方法来操作 ModelAndView 对象,然后将其渲染到 View 页面,这将是所有 Controller 的公共(public)点。

关于java - Spring MVC/Rest - 返回标准响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26060473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com