Java EE – multiple response HTTP states in spring MVC

With the following codes:

@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
    }
}

I want to return two different HTTP statuses according to my logic What is the best way to achieve this goal?

Solution

One method proposed in so is to throw different exceptions, which will be caught by different exception handlers:

@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() {

}

You can also see:

> @ExceptionHandler > @ResponseStatus

BTW, your sample code contains an error: login Password = = "test" you should use equals()

Update: I found another method better because it doesn't use exceptions:

@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);
}

See responseentity API

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>