尝试在Spring REST控制器中返回对象时,出现HTTP状态406 –不可接受的错误

问题描述

在这里,我正在尝试更新对象,并在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);

}

UserResponse类:

@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.

解决方法

您混合了JAX-RS和Spring MVC批注:@RequestMapping来自Spring,@Produces来自JAX-RS。如果看一下@RequestMapping的{​​{3}},您会发现它有一个produces参数。所以你应该有这样的东西:

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