我已经使用像这样的控制器构建了一个JSON REST服务:
@Controller @RequestMapping(value = "/scripts") public class ScriptController { @Autowired private ScriptService scriptService; @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<Script> get() { return scriptService.getScripts(); } }
它工作正常,但现在我需要修改所有响应并将“状态”和“消息”字段添加到所有响应中。我已经阅读了一些解决方案:
public class RestResponse { private int status; private String message; private Object data; public RestResponse(int status, String message, Object data) { this.status = status; this.message = message; this.data = data; } //getters and setters }
如果使用spring 4.1或更高版本,则可以在编写正文之前使用ResponseBodyAdvice定制响应。