簡體   English   中英

獲取 HTTP 狀態 406 – 嘗試在 Spring 中返回 object 時出現不可接受的錯誤 REST controller

[英]Getting HTTP Status 406 – Not Acceptable error when trying to return an object in Spring REST controller

在這里,我正在嘗試更新 object 並以 JSON 格式返回更新后的 object Spring REST controller。

Controller:

@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);

}

用戶響應 class:

@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來自@Produces ,@Produces 來自 JAX-RS。 如果您查看@RequestMapping文檔,您會發現它有一個produces參數。 所以你應該有這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM