最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服!

相关参考: 
Spring 注解学习手札(一) 构建简单Web应用 
Spring 注解学习手札(二) 控制层梳理 
Spring 注解学习手札(三) 表单页面处理 
Spring 注解学习手札(四) 持久层浅析 
Spring 注解学习手札(五) 业务层事务处理 
Spring 注解学习手札(六) 测试 
Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable 
Spring 注解学习手札(八) 补遗——@ExceptionHandler 

SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。再也不用为了组装协议而劳烦辛苦了!

一、Spring注解@ResponseBody,@RequestBody和HttpMessageConverter

Spring 3.X系列增加了新注解@ResponseBody@RequestBody

  • @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
  • @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。

HttpMessageConverter接口,需要开启<mvc:annotation-driven  />。 
AnnotationMethodHandlerAdapter将会初始化7个转换器,可以通过调用AnnotationMethodHandlerAdaptergetMessageConverts()方法来获取转换器的一个集合 List<HttpMessageConverter>

引用
ByteArrayHttpMessageConverter 
StringHttpMessageConverter 
ResourceHttpMessageConverter 
SourceHttpMessageConverter 
XmlAwareFormHttpMessageConverter 
Jaxb2RootElementHttpMessageConverter 
MappingJacksonHttpMessageConverter

可以理解为,只要有对应协议的解析器,你就可以通过几行配置,几个注解完成协议——对象的转换工作!

PS:Spring默认的json协议解析由Jackson完成。

二、servlet.xml配置

Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:

  1. <context:component-scan base-package="org.zlex.json.controller" />
  2. <context:annotation-config />
  3. <mvc:annotation-driven />

三、pom.xml配置

闲言少叙,先说依赖配置,这里以Json+Spring为参考: 
pom.xml

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-webmvc</artifactId>
  4. <version>3.1.2.RELEASE</version>
  5. <type>jar</type>
  6. <scope>compile</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.codehaus.jackson</groupId>
  10. <artifactId>jackson-mapper-asl</artifactId>
  11. <version>1.9.8</version>
  12. <type>jar</type>
  13. <scope>compile</scope>
  14. </dependency>
  15. <dependency>
  16. <groupId>log4j</groupId>
  17. <artifactId>log4j</artifactId>
  18. <version>1.2.17</version>
  19. <scope>compile</scope>
  20. </dependency>

主要需要spring-webmvcjackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。 
包依赖图: 

至于版本,看项目需要吧!

四、代码实现

域对象:

  1. public class Person implements Serializable {
  2. private int id;
  3. private String name;
  4. private boolean status;
  5. public Person() {
  6. // do nothing
  7. }
  8. }

这里需要一个空构造,由Spring转换对象时,进行初始化。

@ResponseBody,@RequestBody,@PathVariable 
控制器:

  1. @Controller
  2. public class PersonController {
  3. /**
  4. * 查询个人信息
  5. *
  6. * @param id
  7. * @return
  8. */
  9. @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)
  10. public @ResponseBody
  11. Person porfile(@PathVariable int id, @PathVariable String name,
  12. @PathVariable boolean status) {
  13. return new Person(id, name, status);
  14. }
  15. /**
  16. * 登录
  17. *
  18. * @param person
  19. * @return
  20. */
  21. @RequestMapping(value = "/person/login", method = RequestMethod.POST)
  22. public @ResponseBody
  23. Person login(@RequestBody Person person) {
  24. return person;
  25. }
  26. }

备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。 这是restful式风格。 
如果映射名称有所不一,可以参考如下方式:

  1. @RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)
  2. public @ResponseBody
  3. Person porfile(@PathVariable("id") int uid) {
  4. return new Person(uid, name, status);
  5. }
  • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
  • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
  • @ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。

做个页面测试下: 
JS

  1. $(document).ready(function() {
  2. $("#profile").click(function() {
  3. profile();
  4. });
  5. $("#login").click(function() {
  6. login();
  7. });
  8. });
  9. function profile() {
  10. var url = 'http://localhost:8080/spring-json/json/person/profile/';
  11. var query = $('#id').val() + '/' + $('#name').val() + '/'
  12. + $('#status').val();
  13. url += query;
  14. alert(url);
  15. $.get(url, function(data) {
  16. alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
  17. + data.status);
  18. });
  19. }
  20. function login() {
  21. var mydata = '{"name":"' + $('#name').val() + '","id":"'
  22. + $('#id').val() + '","status":"' + $('#status').val() + '"}';
  23. alert(mydata);
  24. $.ajax({
  25. type : 'POST',
  26. contentType : 'application/json',
  27. url : 'http://localhost:8080/spring-json/json/person/login',
  28. processData : false,
  29. dataType : 'json',
  30. data : mydata,
  31. success : function(data) {
  32. alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "
  33. + data.status);
  34. },
  35. error : function() {
  36. alert('Err...');
  37. }
  38. });

Table

  1. <table>
  2. <tr>
  3. <td>id</td>
  4. <td><input id="id" value="100" /></td>
  5. </tr>
  6. <tr>
  7. <td>name</td>
  8. <td><input id="name" value="snowolf" /></td>
  9. </tr>
  10. <tr>
  11. <td>status</td>
  12. <td><input id="status" value="true" /></td>
  13. </tr>
  14. <tr>
  15. <td><input type="button" id="profile" value="Profile——GET" /></td>
  16. <td><input type="button" id="login" value="Login——POST" /></td>
  17. </tr>
  18. </table>

四、简单测试

Get方式测试: 

Post方式测试: 

五、常见错误 
POST操作时,我用$.post()方式,屡次失败,一直报各种异常: 

引用
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

直接用$.post()直接请求会有点小问题,尽管我标识为json协议,但实际上提交的ContentType还是application/x-www-form-urlencoded。需要使用$.ajaxSetup()标示下ContentType

  1. function login() {
  2. var mydata = '{"name":"' + $('#name').val() + '","id":"'
  3. + $('#id').val() + '","status":"' + $('#status').val() + '"}';
  4. alert(mydata);
  5. $.ajaxSetup({
  6. contentType : 'application/json'
  7. });
  8. $.post('http://localhost:8080/spring-json/json/person/login', mydata,
  9. function(data) {
  10. alert("id: " + data.id + "\nname: " + data.name
  11. + "\nstatus: " + data.status);
  12. }, 'json');
  13. };

效果是一样!

详见附件!

@ResponseBody,@RequestBody,@PathVariable的更多相关文章

  1. 转-Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable

    转-http://snowolf.iteye.com/blog/1628861/ Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariab ...

  2. Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable (转)

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  3. Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable(转)

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  4. @RequestMapping 和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法

    接下来讲解一下 @RequestMapping  和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法 @RequestMapping 为url映射路 ...

  5. @RequestParam,@RequestBody,@ResponseBody,@PathVariable注解的一点小总结

    一.前提知识: http协议规定一次请求对应一次响应,根据不同的请求方式,请求的内容会有所不同: 发送GET请求是没有请求体的,参数会直接拼接保留到url后一并发送: 而POST请求是带有请求体的,带 ...

  6. @RequestMapping、@Responsebody、@RequestBody和@PathVariable详解(转)

    一.预备知识:@RequestMapping RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上.用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径. @Requ ...

  7. SpringMVC使用@PathVariable,@RequestBody,@ResponseBody,@RequestParam,@InitBinder

    @Pathvariable public ResponseEntity<String> ordersBack(           @PathVariable String reqKey, ...

  8. SpringMVC 之 @ResponseBody 和 @RequestBody

    前后端进行数据交互的时候,规定数据交互的格式,使数据交互规范而统一,是极为重要的事.一般而言,我们会采用 JSON 进行数据交互.本文暂不讨论如何 JSON 的格式规范,而是解析一下如何在 Sprin ...

  9. Spring注解@ResponseBody,@RequestBody

    @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象. @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMess ...

随机推荐

  1. UIScrollViewDelegate 方法调用

    UIScrollViewDelegate 方法调用 /** 设置缩放的View, 初始化完之后调用此方法告诉scrollView 谁可以缩放操作, 然后进行布局 */ func viewForZoom ...

  2. Python Random模块生成伪随机数字

    This module implements pseudo-random number generators for various distributions. 对于整数,有一个范围的均匀选择: 对 ...

  3. 「caffe编译bug」.build_release/lib/libcaffe.so: undefined reference to cv::imread

    转自:https://www.douban.com/note/568788483/ CXX/LD -o .build_release/tools/convert_imageset.bin.build_ ...

  4. (正则表达式)linux shell 字符串操作(长度,查找,替换,匹配)详解

    在做shell批处理程序时候,经常会涉及到字符串相关操作.有很多命令语句,如:awk,sed都可以做字符串各种操作. 其实shell内置一系列操作符号,可以达到类似效果,大家知道,使用内部操作符会省略 ...

  5. Bootstrap的使用。。。

    概览 深入了解 Bootstrap 底层结构的关键部分,包括我们让 web 开发变得更好.更快.更强壮的最佳实践. HTML5 文档类型 Bootstrap 使用到的某些 HTML 元素和 CSS 属 ...

  6. POJ 2752 Seek the Name, Seek the Fame(KMP求公共前后缀)

    题目链接:http://poj.org/problem?id=2752 题目大意:给你一串字符串s找到所有的公共前后缀,即既是前缀又是后缀的子串. 解题思路: 如图所示 假设字符串pi与jq为符合条件 ...

  7. Templated Helper Methods

    1.Model 2.HomeController 3.CreatePerson.cshtml 禁用了客户端验证 4.Using Templated Helper Methods Editor 和 Ed ...

  8. 4款Github泄漏敏感信息搜索工具简单比较

    gitrob Ruby开发,支持通过postgresql数据库https://github.com/michenriksen/gitrob weakfilescan Python开发,多线程,猪猪侠开 ...

  9. 获取 web 项目的绝对路径

    获取 web 项目的绝对路径 <% String path = request.getContextPath(); String basePath = request.getScheme()+& ...

  10. CentOS 7安装Mysql并设置开机自启动的方法

    CentOS 7不带Mysql数据库了,默认的数据库是MariaDB(Mysql的一个分支). 可以按照以下步骤手动安装Mysql数据库. 1. 下载rpm安装文件 ? 1 wget http://r ...