使用Spring MVC构建RESTful应用

3月 21, 2015 |

Demo 下载:spring-mvc-rest.zip

原理简介:

主流的浏览器在实现http1.1协议时基本都只实现了GET和POST方法,rest提倡使用http原本的语义:使用GET获取资源,使用POST新建资源,使用DELETE删除资源,使用PUT更新资源。为了透明的实现DELETE和PUT方法,spring mvc提供了一个spring form标签库,在浏览器中看看最后产生的html代码就一目了然。当我们在jsp页面声明一个<sf:form>元素时,所有的POST,DELETE, PUT方法都是通过POST提交的,只是针对DELETE,PUT产生一个隐藏域来标示实际的http 方法。为了将POST替换成具体的http方法,我们在web.xml中配置HiddenHttpMethodFilter来完成这个动作。

为了根据请求中的Accept头产生相适应的响应,比如Accept="application/json"那么返回json字符串。spring MVC提供了ResponseBody注解,当一个方法的返回值被ResponseBody注解所修饰,那么就不会使用view resolver来渲染视图,而是使用MessageConverter将方法的返回值转换成客户端希望的格式。

实现步骤:

1、使用maven的maven-archetype-webapp向导创建一个maven web工程
2、修改pom.xml添加对应的依赖,包括spring mvc的依赖,json库, 如果要返回xml需要添加jaxb库。
3、修改修改web.xml声明HiddenHttpMethodFilter和DispatchServlet
4、创建spring的Application Context文件mvc-servlet.xml,在这个文件中,我主要配置了一下的信息:
<mvc:resources>静态资源的的请求都映射到/resources/目录
<mvc:annotation-driven/> 和<context:component-scan base-package="cn.javacoder.restdemo.controller"/>启用注解驱动的bean注册机制,将cn.javacoder.restdemo.controller包下所有的用@Controller, @Component, @Service注解的类注册到spring容器中。
InternalResourceViewResolver配置了一个view resolver。
5、在WEB-INF下创建jsp\rest.jsp文件。演示了spring form标签库的使用,主要是使用spring from发起一个PUT 请求和对象域绑定。
6、本demo涉及到两个java文件,UserController.java(Controller,处理http请求) 和User.java(dto对象,为了能自动转换为xml,添加了jaxb注解)

测试:

使用maven执行jetty:run来启动jetty server
1)执行rest GET请求
http://localhost:8080/spring-mvc-rest/rest

效果如图:
rest-demo
2)点击提交,触发PUT请求
3)测试MessageConverter
http://localhost:8080/spring-mvc-rest/testConverter
对于firefox, 执行以下步骤来发送Accept="application/json"的请求:
在浏览器地址栏输入about:config -> 点击 "I'll be careful , i promise" ->在搜索框中输入network.http.accept.default ->将它的值由"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"改为"application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"

相关阅读:

并不是每个人都赞同rest:
http://stackoverflow.com/questions/2191049/what-is-the-advantage-of-using-rest-instead-of-non-rest-http
《Spring IN Action》

Posted in: spring practise | Tags: ,

Comments are closed.