Spring MVC中的多响应http状态 [英] Multiple response http status in Spring MVC

查看:130
本文介绍了Spring MVC中的多响应http状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有以下代码:

@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状态。实现这一目标的最佳方法是什么?

I would like to return two different HTTP statuses based on my logic. What is the best way to achieve this?

推荐答案

有人在SO建议的一种方法是抛出不同的例外情况由不同的异常处理程序:

One approach which someone suggested at SO is to throw different exceptions which will be catch 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() {

}

参见:

  • @ExceptionHandler
  • @ResponseStatus

BTW,您的示例代码包含错误: login。密码==测试你应该使用 equals()那里:)

BTW, your example code contains error: login.password == "test" you should use equals() there :)

已更新:我发现了另一种更好的方法,因为它不使用例外:

Updated: I found another approach which even 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);
}

参见ResponseEntity API

这篇关于Spring MVC中的多响应http状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆