【问题标题】:Getting HTTP Status 406 – Not Acceptable error when trying to return an object in Spring REST controller获取 HTTP 状态 406 - 尝试在 Spring REST 控制器中返回对象时出现不可接受的错误
【发布时间】:2020-10-07 11:44:44
【问题描述】:

这里我正在尝试更新一个对象并在 Spring REST 控制器中以 JSON 格式返回更新后的对象。

控制器:

@RequestMapping(value = "/user/revert", method = RequestMethod.POST)
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public ResponseEntity<UserResponse> revertUserData(@RequestParam(value = "userName") String userName) {

    User user = new User();
    UserResponse userResponse = new UserResponse();

    try {
        user = userService.findUserByName(userName);
        user.setLastName(null);

        userResponse.setEmail(user.getEmail());
        userResponse.setLastName(user.getLastName());

    } catch (Exception e) {
        return new ResponseEntity<UserResponse>(userResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<UserResponse>(userResponse, HttpStatus.OK);

}

用户响应类:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserResponse {

  @JsonProperty("email")
  private String email;
  @JsonProperty("lastName")
  private String lastName;

  //getter and setter methids 

}

pom 文件:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.1</version>
    </dependency>

我得到的错误:

The target resource does not have a current representation that would be acceptable to the
user agent, according to the proactive negotiation header fields received in the request, and the server is
unwilling to supply a default representation.

【问题讨论】:

  • 这表示没有设置标题。您的RequestMapping 中可能缺少produces。见stackoverflow.com/questions/53513644/…
  • 无法将 'produces= MediaType.APPLICATION_JSON' 参数解析到控制器。只有标题有

标签: java json spring spring-restcontroller http-error


【解决方案1】:

您混合了 JAX-RS 和 Spring MVC 注释:@RequestMapping 来自 Spring,@Produces 来自 JAX-RS。如果您查看@RequestMappingdocumentation,您会发现它有一个produces 参数。所以你应该有类似的东西:

@RequestMapping(value = "/user/revert", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
public ResponseEntity<UserResponse> revertUserData(@RequestParam(value = "userName") String userName){
...
}

【讨论】:

猜你喜欢
  • 2014-06-16
  • 2018-07-22
  • 2019-04-30
  • 2018-01-10
  • 2016-06-10
  • 2016-08-11
  • 2015-10-15
  • 2015-03-17
  • 1970-01-01
相关资源
最近更新 更多