有以下代码:
@RequestMapping(value = "/system/login", method = RequestMethod.GET)
public void login(@RequestBody Login login) {
if(login.username == "test" && login.password == "test") {
//return HTTP 200
}
else {
//return HTTP 400
}
}
我想根据我的逻辑返回两个不同的 HTTP 状态。实现这一目标的最佳方法是什么?
有人在 SO 上建议的一种方法是抛出不同的异常,这些异常将由不同的异常处理程序捕获:
@RequestMapping(value = "/system/login", method = RequestMethod.GET)
public void login(@RequestBody Login login) {
if(login.username == "test" && login.password == "test") {
throw new AllRightException();
}
else {
throw new AccessDeniedException();
}
}
@ExceptionHandler(AllRightException.class)
@ResponseStatus(HttpStatus.OK)
public void whenAllRight() {
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void whenAccessDenied() {
}
也可以看看:
- @ExceptionHandler http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-exceptionhandler
- @ResponseStatus http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html
顺便说一句,您的示例代码包含错误:login.password == "test"
你应该使用equals()
那里 :)
Updated:我发现了另一种更好的方法,因为它不使用异常:
@RequestMapping(value = "/system/login", method = RequestMethod.GET)
public ResponseEntity<String> login(@RequestBody Login login) {
if(login.username == "test" && login.password == "test") {
return new ResponseEntity<String>("OK" HttpStatus.OK);
}
return new ResponseEntity<String>("ERROR", HttpStatus.BAD_REQUEST);
}
也可以看看响应实体API http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/ResponseEntity.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)