您的位置:首页 > 编程语言 > Java开发

Spring REST

2011-06-10 11:08 405 查看
前面介绍过Spring的MVC结合不同的view显示不同的数据,如:结合json的view显示json、结合xml的view显示xml文档。那么这些数据除了在WebBrowser中用JavaScript来调用以外,还可以用远程服务器的Java程序、C#程序来调用。也就是说现在的程序不仅在BS中能调用,在CS中同样也能调用,不过你需要借助RestTemplate这个类来完成。RestTemplate有点类似于一个WebService客户端请求的模版,可以调用http请求的WebService,并将结果转换成相应的对象类型。至少你可以这样理解!上一次博文介绍SpringMVC结合不同的View,显示不同的数据。/article/4791853.htmlEmail:hoojo_@126.comBlog:http://blog.csdn.net/IBM_hoojohttp://hoojo.cnblogs.com/

一、准备工作

1、下载jar包spring各版本jar下载地址:http://ebr.springsource.com/repository/app/library/detail?name=org.springframework.spring相关的依赖包也可以在这里找到:http://ebr.springsource.com/repository/app/library2、需要jar包如下

3、当前工程的web.xml配置
[code]<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
'target='_blank'>http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--配置Spring核心控制器-->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
[/code]
4、WEB-INF中的dispatcher.xml配置
[code]<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
'target='_blank'>http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
'target='_blank'>http://www.springframework.org/schema/mvc
'target='_blank'>http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
'target='_blank'>http://www.springframework.org/schema/context/spring-context-3.0.xsd
'target='_blank'>http://www.springframework.org/schema/util
'target='_blank'>http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scanbase-package="com.hoo.*">
<!--忽略这个类-->
<context:exclude-filtertype="assignable"expression="com.hoo.client.RESTClient"/>
</context:component-scan>
<!--annotation的方法映射适配器-->
<beanid="handlerAdapter"class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!--xml视图,XStreamMarshaller,可以转换任何形式的java对象-->
<beanname="xStreamMarshallingView"class="org.springframework.web.servlet.view.xml.MarshallingView">
<propertyname="marshaller">
<beanclass="org.springframework.oxm.xstream.XStreamMarshaller">
<!--为了初始化XStreamMarshaller,这个类会把我们接口中得到结果以XML文档形式展现出来-->
<propertyname="autodetectAnnotations"value="true"/>
</bean>
</property>
</bean>
<!--视图解析器,根据视图的名称newModelAndView(name),在配置文件查找对应的bean配置-->
<beanclass="org.springframework.web.servlet.view.BeanNameViewResolver">
<propertyname="order"value="3"/>
</bean>
<!--annotation默认的方法映射适配器-->
<beanid="handlerMapping"class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<propertyname="order"value="1"/>
</bean>
</beans>
[/code]
5、启动后,可以看到index.jsp没有出现异常或错误。那么当前SpringMVC的配置就成功了。

二、REST控制器实现

REST控制器主要完成CRUD操作,也就是对于http中的post、get、put、delete。
还有其他的操作,如head、options、trace。
具体代码:

[code]packagecom.hoo.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.servlet.ModelAndView;
/**
*<b>function:</b>SpringMVCREST示例
*@authorhoojo
*@createDate2011-6-9上午11:34:08
*@fileRESTController.java
*@packagecom.hoo.controller
*@projectSpringRestWS
*@blog
'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
@RequestMapping("/restful")
@Controller
publicclassRESTController{
@RequestMapping(value="/show",method=RequestMethod.GET)
publicModelAndViewshow(){
System.out.println("show");
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("showmethod");
returnmodel;
}
@RequestMapping(value="/get/{id}",method=RequestMethod.GET)
publicModelAndViewgetUserById(@PathVariableStringid){
System.out.println("getUserById-"+id);
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("getUserByIdmethod-"+id);
returnmodel;
}
@RequestMapping(value="/add",method=RequestMethod.POST)
publicModelAndViewaddUser(Stringuser){
System.out.println("addUser-"+user);
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("addUsermethod-"+user);
returnmodel;
}
@RequestMapping(value="/edit",method=RequestMethod.PUT)
publicModelAndVieweditUser(Stringuser){
System.out.println("editUser-"+user);
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("editUsermethod-"+user);
returnmodel;
}
@RequestMapping(value="/remove/{id}",method=RequestMethod.DELETE)
publicModelAndViewremoveUser(@PathVariableStringid){
System.out.println("removeUser-"+id);
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("removeUsermethod-"+id);
returnmodel;
}
}
[/code]
上面的方法对应的http操作:

[code]/show->get查询
/get/id->get查询
/add->post添加
/edit->put修改
/remove/id->delete删除
[/code]
在这个方法中,就可以看到RESTful风格的url资源标识

[code]@RequestMapping(value="/get/{id}",method=RequestMethod.GET)
publicModelAndViewgetUserById(@PathVariableStringid){
System.out.println("getUserById-"+id);
ModelAndViewmodel=newModelAndView("xStreamMarshallingView");
model.addObject("getUserByIdmethod-"+id);
returnmodel;
}
[/code]
value=”/get/{id}”就是url中包含get,并且带有id参数的get请求,就会执行这个方法。这个url在请求的时候,会通过Annotation的@PathVariable来将url中的id值设置到getUserById的参数中去。ModelAndView返回的视图是xStreamMarshallingView是一个xml视图,执行当前请求后,会显示一篇xml文档。文档的内容是添加到model中的值。

三、利用RestTemplate调用REST资源

代码如下:

[code]packagecom.hoo.client;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Component;
importorg.springframework.web.client.RestTemplate;
/**
*<b>function:</b>RestTemplate调用REST资源
*@authorhoojo
*@createDate2011-6-9上午11:56:16
*@fileRESTClient.java
*@packagecom.hoo.client
*@projectSpringRestWS
*@blog
'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
@Component
publicclassRESTClient{
@Autowired
privateRestTemplatetemplate;
privatefinalstaticStringurl="http://localhost:8080/SpringRestWS/restful/";
publicStringshow(){
returntemplate.getForObject(url+"show.do",String.class,newString[]{});
}
publicStringgetUserById(Stringid){
returntemplate.getForObject(url+"get/{id}.do",String.class,id);
}
publicStringaddUser(Stringuser){
returntemplate.postForObject(url+"add.do?user={user}",null,String.class,user);
}
publicStringeditUser(Stringuser){
template.put(url+"edit.do?user={user}",null,user);
returnuser;
}
publicStringremoveUser(Stringid){
template.delete(url+"/remove/{id}.do",id);
returnid;
}
}
[/code]
RestTemplate的getForObject完成get请求、postForObject完成post请求、put对应的完成put请求、delete完成delete请求;还有execute可以执行任何请求的方法,需要你设置RequestMethod来指定当前请求类型。
RestTemplate.getForObject(Stringurl,Class<String>responseType,String...urlVariables)
参数url是http请求的地址,参数Class是请求响应返回后的数据的类型,最后一个参数是请求中需要设置的参数。
template.getForObject(url+"get/{id}.do",String.class,id);
如上面的参数是{id},返回的是一个string类型,设置的参数是id。最后执行该方法会返回一个String类型的结果。
下面建立一个测试类,完成对RESTClient的测试。代码如下:

[code]packagecom.hoo.client;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
/**
*<b>function:</b>RESTClientTEST
*@authorhoojo
*@createDate2011-6-9下午03:50:21
*@fileRESTClientTest.java
*@packagecom.hoo.client
*@projectSpringRestWS
*@blog
'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
@ContextConfiguration("classpath:applicationContext-*.xml")
publicclassRESTClientTestextendsAbstractJUnit38SpringContextTests{
@Autowired
privateRESTClientclient;
publicvoidtestShow(){
System.out.println(client.show());
}
publicvoidtestGetUserById(){
System.out.println(client.getUserById("abc"));
}
publicvoidtestAddUser(){
System.out.println(client.addUser("jack"));
}
publicvoidtestEditUser(){
System.out.println(client.editUser("tom"));
}
publicvoidtestRemoveUser(){
System.out.println(client.removeUser("aabb"));
}
}
[/code]
我们需要在src目录下添加applicationContext-beans.xml完成对restTemplate的配置。restTemplate需要配置MessageConvert将返回的xml文档进行转换,解析成JavaObject。
[code]<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
'target='_blank'>http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
'target='_blank'>http://www.springframework.org/schema/context
'target='_blank'>http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scanbase-package="com.hoo.*"/>
<beanid="restTemplate"class="org.springframework.web.client.RestTemplate">
<propertyname="messageConverters">
<list>
<beanclass="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<propertyname="marshaller"ref="xStreamMarshaller"/>
<propertyname="unmarshaller"ref="xStreamMarshaller"/>
</bean>
</list>
</property>
</bean>
<beanid="xStreamMarshaller"class="org.springframework.oxm.xstream.XStreamMarshaller">
<propertyname="annotatedClasses">
<array>
</array>
</property>
</bean>
</beans>
[/code]
上面配置了xStreamMarshaller是和RESTController中的ModelAndView的view对应的。因为那边是用xStreamMarshaller进行编组的,所以RestTemplate这边也需要用它来解组。RestTemplate还指出其他的MarshallingHttpMessageConverter;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: