首先说RESTful 风格是什么 :(RESTful 风格:把请求参数变成请求路径的一种风格。) OK,一句话总结完毕

@responsebody表示该方法的返回结果直接写入HTTP response body中一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。

SpringMVC层跟JSon结合,几乎不需要做什么配置,代码实现也相当简洁。妈妈再也不用担心组装协议
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. };

效果是一样!

详见附件!

												

SpringMVC随笔之——@responsebody【引用snowolf博文】的更多相关文章

  1. SpringMVC中通过@ResponseBody返回对象,Js中调用@ResponseBody返回值,统计剩余评论字数的js,@RequestParam默认值,@PathVariable的用法

    1.SpringMVC中通过@ResponseBody.@RequestParam默认值,@PathVariable的用法 package com.kuman.cartoon.controller.f ...

  2. springMvc注解之@ResponseBody和@RequestBody

    简介 springmvc对json的前后台传输做了很好封装,避免了重复编码的过程,下面来看看常用的@ResponseBody和@RequestBody注解 添加依赖 springmvc对json的处理 ...

  3. SpringMvc HttpMessageConverter之@ResponseBody

    我们先看HttpMessageConverter的示意图,从图片可以看出它是多么的重要.在一条必经之路截道了的感觉. 先上我的测试例子: jsp页面: <%@ page language=&qu ...

  4. springMVC笔记:@ResponseBody

    使用@ResponseBody的方式,将Map形返回值转为json,用作POST请求的返回值.为了解决406 Not Acceptable错误,需要检查以下几项: 1. 依赖包中包含jackson-m ...

  5. SpringMVC随笔记录

    在web.xml里可以配置webapp的默认首页,格式如下: <welcome-file-list> <welcome-file>index.html</welcome- ...

  6. SpringMVC框架09——@ResponseBody的用法详解

    @ResponseBody可以标注在方法上也可以标注在类上面.简单来说,当标注在方法上时,该方法的返回结果直接转成JSON格式:当标注在类上时,该类中的所有方法的返回结果都转换成JSON格式. 代码示 ...

  7. SpringMVC学习八 @ResponseBody注解

    (一)在方法上只有@RequestMapping 时,无论方法返回值是什么认为需要跳转,代码实例如下 @RequestMapping("demo10") public People ...

  8. SpringMVC中使用@ResponseBody注解将任意POJO对象返回值转换成json进行返回

    @ResponseBody 作用: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区. ...

  9. SpringMVC中 解决@ResponseBody注解返回中文乱码

    问题:在前端通过get请求服务端返回String类型的服务时,会出现中文乱码问题 原因:由于spring默认对String类型的返回的编码采用的是 StringHttpMessageConverter ...

随机推荐

  1. ie6 PNG图片透明

    _background:none; _filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=images/videoTips.pn ...

  2. IIS 域名 带参数 设置重定向

    IIS里面设置重定向后,经常会出现,从百度快照里直接打不开的情况. 可以在IIS里面设置重定向的时候,把参数加上,格式如下: http://www.***.com%S%Q

  3. (转)HTTP 错误 404.2 - Not Found 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面

    详细错误:HTTP 错误 404.2 - Not Found. 由于 Web 服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面. 出现环境:win7 + IIS7.0 解决办法 ...

  4. 多进程copy文件

    from multiprocessing import Pool,Manager import os,time def copyFileTask(fileName,oldFolderName,newF ...

  5. CF402D Upgrading Array

    原题链接 先用素数筛筛下素数,然后考虑贪心去操作. 先求前缀\(GCD\)(求到\(GCD\)为\(1\)就不用再往下求了),得到数组\(G[i]\),然后从后往前扫,如果\(f(G[i]) < ...

  6. a label can only be part of statement and a declaratioin is not a statement

    参考资料: https://stackoverflow.com/questions/18496282/why-do-i-get-a-label-can-only-be-part-of-a-statem ...

  7. RecyclerView错误

    1. java.lang.NoClassDefFoundError: android.support.v7.widget.RecyclerView 这个错误真TM见鬼,明明jar包里面就有这个类,工程 ...

  8. js实现多标签页效果

    点击导航按钮切换div的内容 html代码: <div class="tabs"> <ul id="tab"> <li>&l ...

  9. 20155312 2016-2017-2 《Java程序设计》第九周学习总结

    20155312 2016-2017-2 <Java程序设计>第九周学习总结 课堂内容总结 两个类有公用的东西放在父类里. 面向对象的三要素 封装 继承 多态:用父类声明引用,子类生成对象 ...

  10. 5. Longest Palindromic Substring - Unsolved

    https://leetcode.com/problems/longest-palindromic-substring/#/description Given a string s, find the ...