本文翻译自: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

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

  1. Spring MVC同一方法返回JSON/XML格式

    最近一道面试题,要求同一API接口支持不同格式返回值.一开始是设想通过过滤器(Filter)设置返回值,但是并不可行,因为方法返回值一般都是类型需要做转换,而过滤器则是前置的.另一方面可以通过拦截器的 ...

  2. Spring MVC和REST中@RestController和@Controller注释之间的区别

    Spring MVC中的@RestController注释不过是@Controller和@ResponseBody注释的组合. 它已添加到Spring 4.0中,以简化在Spring框架中RESTfu ...

  3. HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面

    默认的Tomcat错误页面看起来很可怕. 此外,它们可能会公开有价值的信息,包括服务器版本和异常堆栈跟踪. Servlet规范提供了一种通过web.xml配置异常行为的方法. 可以配置对特定Java异 ...

  4. Spring MVC应用程序中的Thymeleaf模板布局,无扩展

    在使用JSP / JSTL和Apache Tiles几年之后,我开始为我的Spring MVC应用程序发现Thymeleaf. Thymeleaf是一个非常出色的视图引擎,尽管目前缺乏良好的Intel ...

  5. 在Spring MVC应用程序中使用Bean Validation 1.1获得更好的错误消息

    在许多新功能中, Bean Validation 1.1引入了使用统一表达式语言(EL)表达式的错误消息插值. 这允许基于条件逻辑来定义错误消息,还可以启用高级格式化选项 . 添加到Spring MV ...

  6. spring mvc在Controller中获取ApplicationContext

    spring mvc在Controller中获取ApplicationContext web.xml中进行正常的beans.xml和spring-mvc.xml的配置: 需要在beans.xml中进行 ...

  7. Spring MVC 在JSP中获取 Service或Dao

    Spring MVC 在JSP中获取service 在Controller.Service层都已经配置好了自动注入,但是在JSP中直接使用 IuserInfoShService uishService ...

  8. java注解返回不同消息,Spring MVC Controller中的一个读入和返回都是JSON的方法如何获取javax.validation注解的异常信息...

    Spring MVC Controller中的一个读入和返回都是JSON的方法怎么获取javax.validation注解的错误信息? 本帖最后由 LonelyCoder2012 于 2014-03- ...

  9. SSM框架之Spring MVC(三)http响应、文件上传

    一.响应数据和结果视图 1.1 返回值分类 1.1.1 字符串 创建实体类和controller类 实体类User package cn.xiaomifeng1010.domain;import ja ...

最新文章

  1. 【Golang源码分析】Go Web常用程序包gorilla/mux的使用与源码简析
  2. SpringCloud 01_单体应用到分布式系统演变过程
  3. vivo C/C++工程师 HR视频面试问题总结20180807
  4. python自动化输入不了中文_appium+python自动化61-中文输入乱码问题解决
  5. 计算机网络课程设计之基于 IP 多播的网络会议程序
  6. Java基础SQL优化---面试题【一】
  7. 失败的面试小记,项目面,酷家乐面筋
  8. 修改win10服务器登录密码,玩转Win10密码基础篇:设置修改系统登录密码
  9. 长连接和短链接在服务器占用资源,TCP长连接和短链接及优缺点
  10. 小型网络游戏实例(vc++)——网络五子棋
  11. Manjaro学习笔记
  12. python27安装get-pip
  13. This generated password is for development use only. Your security configuration must be updated bef
  14. 【Java实战篇】SpringBoot+MyBatis快速实现登录注册
  15. centOS 8 报错:Failed to set locale, defaulting to C.UTF-8
  16. 什么是内容电商,内容电商平台有哪些?
  17. 利用Python进行数据分析——数据导入导出
  18. 企业生产管理集成的核心工具—MES管理系统
  19. 真香!红色警戒游戏源代码被开源了!
  20. 最全MySQL8.0实战教程 14 MySQL的存储过程 14.2 入门案例

热门文章

  1. java自定义注解简单小例子
  2. Activity启动过程
  3. FastJson 打Release 包解析失败
  4. 第十、十一周项目三-警察和厨师(2)
  5. 使用Fresco加载图片
  6. 自适应col自动换行显示_10kV配网自适应综合型馈线自动化技术的测试问题及解决措施...
  7. PHP学习笔记-PHP与Web页面的交互2
  8. PHP源码设置超出隐藏,怎样隐藏文本的超出部分
  9. plc通讯的握手信号_MES与PLC握手的几种方式-控制器/处理器-与非网
  10. Android Service与Activity的交互