相关疑难解决方法(0)

如何在返回String的Spring MVC @ResponseBody方法中响应HTTP 400错误?

我使用Spring MVC作为一个简单的JSON API,@ResponseBody基于以下方法.(我已经有一个直接生成JSON的服务层.)

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        // TODO: how to respond with e.g. 400 "bad request"?
    }
    return json;
}
Run Code Online (Sandbox Code Playgroud)

问题是,在给定的场景中,用HTTP 400错误响应的最简单,最干净的方法是什么?

我确实遇到过这样的方法:

return new ResponseEntity(HttpStatus.BAD_REQUEST);
Run Code Online (Sandbox Code Playgroud)

...但我不能在这里使用它,因为我的方法的返回类型是String,而不是ResponseEntity.

java spring spring-mvc http-error

366
推荐指数
8
解决办法
34万
查看次数

标签 统计

http-error ×1

java ×1

spring ×1

spring-mvc ×1