具有以下代码:

@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
  • @ResponseStatus

  • 顺便说一句,您的示例代码包含错误:login.password == "test"您应该在此处使用equals() :)

    更新了:我发现了另一种更好的方法,因为它不使用异常:
    @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

    09-27 05:21