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

本文翻译自: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")
@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;
}

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楼

参考:https://stackoom.com/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 a ModelAndView or something. 如果使用Spring 3.1+,编辑你可以在异常处理程序方法中使用@ResponseBody,否则使用ModelAndView或其他东西。

https://jira.springsource.org/browse/SPR-6902 https://jira.springsource.org/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")
@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;
}

#4楼

change your return type to ResponseEntity<> , 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 a UnknownMatchException : 首先,我创建一个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's ResponseStatusExceptionResolver . 请注意@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 to 404 - Not Found which I find more appropriate for this use case, but you can stick to HttpStatus.BAD_REQUEST if you like.) (我也冒昧地将状态代码更改为404 - Not Found ,我认为更适合此用例,但如果您愿意,可以坚持使用HttpStatus.BAD_REQUEST 。)


Next, I would change the MatchService to have the following signature: 接下来,我将更改MatchService以具有以下签名:

interface MatchService {
    public Match findMatch(String matchId);
}

Finally, I would update the controller and delegate to Spring's MappingJackson2HttpMessageConverter 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)
@ResponseBody
public 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)
@ResponseBody
public 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军事工具:

https://stackoverflow.com/a/16986372/1278921 https://stackoverflow.com/a/16986372/1278921

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值