java - 从 spring Controller 返回空 JSON 以获得无效响应

标签 java rest spring-mvc

我正在使用 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);
}

204 response code :

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/

相关文章:

java - 将 byte[] 解析回 Protocol Buffer 消息实例时出现 RuntimeException! (反序列化)

java - :inputText value inside rich:modalPanel not binding to backing bean

rest - 将 GO map 转换为结构

java - 如何在放心地实现 get 请求时设置特定条件的等待

java - 调用微服务

java - Spring:将字符串从 View 转换为日历对象

java - 在循环中清空数组列表

java - 设置 JVM 选项以避免错误 Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1

java - 关于创建自己的 SSO 的建议——我应该将其公开给 REST 还是将其包装在 API 中?

java - Spring MVC中Quarts调度器多次执行