我正在使用 Java 8、Tomcat 8、Spring-WebMVC 4.2.2.RELEASE、FasterXML 2.6.3。
我的 Controller 中有以下方法
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public void updateCurrentUserDetails(@RequestBody final UserDTO userDTO) {
final UserWithId user = SecurityUtil.getCurrentUser();
this.userAccountService.updateUserDetails(user.getUserId(), user.getUsername(), userDTO);
}
此方法返回 void,解析为空(0 字节)响应。然而,连接到服务器的客户端总是期望 JSON 响应,即使它是一个空响应。
所以我想配置 Spring/Jackson 在这种情况下返回 {}(2 字节)。
我已经考虑过在调用中到处返回 new Object() 否则会返回 void 但我认为这是一个肮脏的解决方案,必须有更好的东西。
最佳答案
没有必要做所有这些。您可以只使用 204
响应代码,它是为您所描述的情况而设计的。您甚至不需要 ResponseBody
注释,只需使用:
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateCurrentUserDetails(@RequestBody final UserDTO userDTO) {
final UserWithId user = SecurityUtil.getCurrentUser();
this.userAccountService.updateUserDetails(user.getUserId(), user.getUsername(), userDTO);
}
The 204 (No Content) status code indicates that the server has
successfully fulfilled the request and that there is no additional
content to send in the response payload body.
关于java - 从 spring Controller 返回空 JSON 以获得无效响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828805/