本文翻译自:How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
I'm using Spring MVC for a simple JSON API, with@ResponseBody
based approach like the following.我正在使用Spring MVC作为一个简单的JSON API,使用基于@ResponseBody
的方法,如下所示。(I already have a service layer producing JSON directly.)(我已经有一个直接生成JSON的服务层。)
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")@ResponseBodypublic 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;}
Question is, in the given scenario,what is the simplest, cleanest way to respond with a HTTP 400 error?问题是,在给定的场景中,用HTTP 400错误响应的最简单,最干净的方法是什么?
I did come across approaches like:我确实遇到过这样的方法:
return new ResponseEntity(HttpStatus.BAD_REQUEST);
...but I can't use it here since my method's return type is String, not ResponseEntity....但我不能在这里使用它,因为我的方法的返回类型是String,而不是ResponseEntity。
#1楼
参考:/question/166tt/如何在返回String的Spring-MVC-ResponseBody方法中响应HTTP-错误
#2楼
Not necessarily the most compact way of doing this, but quite clean IMO不一定是最紧凑的方式,但相当干净的IMO
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");}
Edit you can use @ResponseBody in the exception handler method if using Spring 3.1+, otherwise use aModelAndView
or something.如果使用Spring 3.1+,编辑你可以在异常处理程序方法中使用@ResponseBody,否则使用ModelAndView
或其他东西。
/browse/SPR-6902/browse/SPR-6902
#3楼
Something like this should work, I'm not sure whether or not there is a simpler way:这样的事情应该有效,我不确定是否有更简单的方法:
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")@ResponseBodypublic 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;}
#4楼
change your return type toResponseEntity<>
, then you can use below for 400将您的返回类型更改为ResponseEntity<>
,然后您可以使用下面的400
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
and for correct request并提出正确的要求
return new ResponseEntity<>(json,HttpStatus.OK);
UPDATE 1更新1
after spring 4.1 there are helper methods in ResponseEntity could be used as在4.1之后,ResponseEntity中有辅助方法可以用作
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
and和
return ResponseEntity.ok(json);
#5楼
I would change the implementation slightly:我会稍微改变一下实现:
First, I create aUnknownMatchException
:首先,我创建一个UnknownMatchException
:
@ResponseStatus(HttpStatus.NOT_FOUND)public class UnknownMatchException extends RuntimeException {public UnknownMatchException(String matchId) {super("Unknown match: " + matchId);}}
Note the use of @ResponseStatus , which will be recognized by Spring'sResponseStatusExceptionResolver
.请注意@ResponseStatus的使用,它将被Spring的ResponseStatusExceptionResolver
识别。If the exception is thrown, it will create a response with the corresponding response status.如果抛出异常,它将创建具有相应响应状态的响应。(I also took the liberty of changing the status code to404 - Not Found
which I find more appropriate for this use case, but you can stick toHttpStatus.BAD_REQUEST
if you like.)(我也冒昧地将状态代码更改为404 - Not Found
,我认为更适合此用例,但如果您愿意,可以坚持使用HttpStatus.BAD_REQUEST
。)
Next, I would change theMatchService
to have the following signature:接下来,我将更改MatchService
以具有以下签名:
interface MatchService {public Match findMatch(String matchId);}
Finally, I would update the controller and delegate to Spring'sMappingJackson2HttpMessageConverter
to handle the JSON serialization automatically (it is added by default if you add Jackson to the classpath and add either@EnableWebMvc
or<mvc:annotation-driven />
to your config, see the reference docs ):最后,我会更新控制器并委托Spring的MappingJackson2HttpMessageConverter
自动处理JSON序列化(如果你将Jackson添加到类路径并将@EnableWebMvc
或<mvc:annotation-driven />
到你的配置中,默认情况下会添加它,请参阅参考文档 ):
@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic Match match(@PathVariable String matchId) {// throws an UnknownMatchException if the matchId is not known return matchService.findMatch(matchId);}
Note, it is very common to separate the domain objects from the view objects or DTO objects.注意,将域对象与视图对象或DTO对象分开是很常见的。This can easily be achieved by adding a small DTO factory that returns the serializable JSON object:这可以通过添加一个返回可序列化JSON对象的小型DTO工厂来轻松实现:
@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublic MatchDTO match(@PathVariable String matchId) {Match match = matchService.findMatch(matchId);return MatchDtoFactory.createDTO(match);}
#6楼
I think this thread actually has the easiest, cleanest solution, that does not sacrifice the JSON martialing tools that Spring provides:我认为这个线程实际上有最简单,最干净的解决方案,不会牺牲Spring提供的JSON军事工具:
/a/16986372/1278921/a/16986372/1278921