我需要为我的 REST Web 服务请求设置不同的 HTTP 状态代码。 基本上用户会发送 ISBN 号码,我需要验证它
- 如果用户发送空请求正文,则给出错误消息 ISBN 不能为空 并设置http状态码
- 如果用户提供字母,给出错误消息不允许使用字母并设置适当的http状态代码
- 如果用户提供了错误的格式,则提供错误格式的错误消息并设置不同的 HTTP 状态代码。
- 如果 isbn 无效,则给出错误消息“Not a Valid ISBN number”并设置适当的 HTTP 状态代码。
- 如果 ISBN 号有效,则返回图书名称,http 状态为 200。
我尝试设置 http 状态代码,但它没有反射(reflect)。
@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);
}
<小时/>
public class 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(...)
public ResponseEntity<StatusBean> findBook(@RequestBody String json) throws Exception {
...
if(json==null) {
throw new NullRequestException();
}
if(!isNumeric(json)) {
throw new RequestContainsAlphabetsException();
}
if(!isValidFormat(json)) {
throw new InvalidFormatException();
}
...
}
然后您需要在应用程序级别定义一个自己的全局异常处理程序。在此自定义异常处理程序中,您将捕获抛出的异常并向客户端发送回正确的响应,其中包含自定义错误消息、HTTP 响应代码、时间戳等。
有关更多详细信息,请参阅此 page .
关于java - 根据验证结果设置不同的http状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56279897/