具有以下代码:
@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 } }
解决方法
有人在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() { }
也可以看看:@H_502_5@
> @ExceptionHandler
> @ResponseStatus@H_502_5@
BTW,你的示例代码包含错误:login.password ==“test”你应该使用equals()有:)@H_502_5@
更新:我发现另一种方法更好,因为它不使用例外:@H_502_5@
@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); }
参见ResponseEntity API@H_502_5@