提问者:小点点

如何在返回字符串的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;
}

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

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

return new ResponseEntity(HttpStatus.BAD_REQUEST);

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


共3个答案

匿名用户

将返回类型更改为responseEntity<>,则可以使用下面的400

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

和正确的请求

return new ResponseEntity<>(json,HttpStatus.OK);

更新1

在spring 4.1之后,ResponseEntity中的帮助器方法可以用作

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);

而且

return ResponseEntity.ok(json);

匿名用户

像这样的方法应该行得通,我不确定是否有更简单的方法:

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
    }
    return json;
}

匿名用户

不一定是最紧凑的方式,但相当干净的海事组织

if(json == null) {
    throw new BadThingException();
}
...

@ExceptionHandler(BadThingException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody MyError handleException(BadThingException e) {
    return new MyError("That doesnt work");
}

编辑如果使用spring 3.1+可以在异常处理程序方法中使用@ResponseBody,否则使用modelandview或其他东西。

https://jira.springsource.org/browse/spr-6902