Spring MVC中@ResponseBody方法中如何返回HTTP400错误呢?

书欣 SpringMVC 发布时间:2023-07-12 23:22:45 阅读数:5064 1
下文笔者讲述ResponseBody注解返回http400代码的方法及示例分享
ResponseBody注解返回http400状态码的方法
   借助ResponseEntity对象返回
    在返回ResponseEntity时传入相应的状态码

注意事项
   此种方法必须将返回类型设置为ResponseEntity类型
例:SpringMVC返回http400状态码
 
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
 
    }
    return json;
}

修改为

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public ResponseEntity match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
 
		return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		//或
       return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }
    return return new ResponseEntity<>(json,HttpStatus.OK);;
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringMVC/202307/7073.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者