我需要为我的REST Web服务请求设置不同的HTTP状态代码。
基本上用户会发送ISBN号,我需要验证它
1.如果用户发送空的请求正文,则给出错误消息ISBN不能为空
并设置http状态码
2.如果用户提供了Alphabets,则给出了错误消息,Alphabets不允许,并设置了适当的http状态代码
3.如果用户输入了错误的格式,请给错误消息提供错误的格式,并设置不同的HTTP状态代码。
4.如果isbn无效,则给出错误消息“无效的ISBN号”,并设置适当的HTTP状态代码。
5.如果输入有效的ISBN号,则返回http状态为200的书名。

我尝试设置http状态代码,但未反映出来。

 @RequestMapping(value = "/person", method = RequestMethod.POST,
         consumes = "application/json", produces = "application/json")
    public ResponseEntity<StatusBean>  findBook(@RequestBody String json) {

     StatusBean sb = new StatusBean();
     if(json==null) {
         sb.setMessage("Request Cannot be Null");
            return new ResponseEntity<StatusBean>(sb,HttpStatus.BAD_REQUEST);
     }
     if(!isNumeric(json)) {
         sb.setMessage("Request Cannot have Alphabets Characters");
        //here i need to set different status
         return new ResponseEntity<StatusBean>(sb,HttpStatus.BAD_REQUEST);
     }
     if(!isValidFormat(json)) {
         sb.setMessage("Request Cannot have Alphabets Characters");
         //here i need to set different status
         return new ResponseEntity<StatusBean>(sb,HttpStatus.BAD_REQUEST);
     }
     if(!isValidISBN(json)) {
         sb.setMessage("Request Cannot have Alphabets Characters");
         //here i need to set different status
         return new ResponseEntity<StatusBean>(sb,HttpStatus.BAD_REQUEST);
     }

     Map<String,String> map = new HashMap<>();
        map.put("book", "Effective Java");
        sb.setResponseJSONMap(map);
        return new ResponseEntity<StatusBean>(sb,HttpStatus.OK);
}


公共类StatusBean {

private String message;
private Map<String,String> responseJSONMap;

public String getMessage() {
    return message;
}
public void setMessage(String message) {
    this.message = message;
}
public Map<String, String> getResponseJSONMap() {
    return responseJSONMap;
}
public void setResponseJSONMap(Map<String, String> responseJSONMap) {
    this.responseJSONMap = responseJSONMap;
}


}

最佳答案

 @RequestMapping(value = "/person", method = RequestMethod.POST,
     consumes = "application/json", produces = "application/json")
public ResponseEntity<StatusBean>  findBook(@RequestBody(required=false) String json) {
  // rest of the code
}

尝试对请求正文使用(required = false)。默认情况下,Spring需要请求主体。

10-08 12:58