Spring REST
前面介绍过Spring的MVC结合不同的view显示不同的数据,如:结合json的view显示json、结合xml的view显示xml文档。那么这些数据除了在WebBrowser中用JavaScript来调用以外,还可以用远程服务器的Java程序、C#程序来调用。也就是说现在的程序不仅在BS中能调用,在CS中同样也能调用,不过你需要借助RestTemplate这个类来完成。RestTemplate有点类似于一个WebService客户端请求的模版,可以调用http请求的WebService,并将结果转换成相应的对象类型。至少你可以这样理解!
上一次博文介绍SpringMVC结合不同的View,显示不同的数据。http://www.cnblogs.com/hoojo/archive/2011/04/29/2032571.html
Email:hoojo_@126.com
Blog:http://blog.csdn.net/IBM_hoojo
一、准备工作
1、 下载jar包
spring各版本jar下载地址:http://ebr.springsource.com/repository/app/library/detail?name=org.springframework.spring
相关的依赖包也可以在这里找到:http://ebr.springsource.com/repository/app/library
2、 需要jar包如下
3、 当前工程的web.xml配置
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<web-app version="2.4"<!--CRLF-->
xmlns="http://java.sun.com/xml/ns/j2ee"<!--CRLF-->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<!--CRLF-->
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee<!--CRLF-->
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--CRLF-->
<!--CRLF-->
<!-- 配置Spring核心控制器 -->
<!--CRLF-->
<servlet><!--CRLF-->
<servlet-name>dispatcher</servlet-name><!--CRLF-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--CRLF-->
<init-param><!--CRLF-->
<param-name>contextConfigLocation</param-name><!--CRLF-->
<param-value>/WEB-INF/dispatcher.xml</param-value><!--CRLF-->
</init-param><!--CRLF-->
<load-on-startup>1</load-on-startup><!--CRLF-->
</servlet><!--CRLF-->
<!--CRLF-->
<servlet-mapping><!--CRLF-->
<servlet-name>dispatcher</servlet-name><!--CRLF-->
<url-pattern>*.do</url-pattern><!--CRLF-->
</servlet-mapping><!--CRLF-->
<!--CRLF-->
<welcome-file-list><!--CRLF-->
<welcome-file>index.jsp</welcome-file><!--CRLF-->
</welcome-file-list><!--CRLF-->
</web-app><!--CRLF-->
4、 WEB-INF中的dispatcher.xml配置
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<beans xmlns="http://www.springframework.org/schema/beans"<!--CRLF-->
xmlns:mvc="http://www.springframework.org/schema/mvc"<!--CRLF-->
xmlns:context="http://www.springframework.org/schema/context"<!--CRLF-->
xmlns:util="http://www.springframework.org/schema/util"<!--CRLF-->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<!--CRLF-->
xsi:schemaLocation="http://www.springframework.org/schema/beans<!--CRLF-->
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd<!--CRLF-->
http://www.springframework.org/schema/mvc<!--CRLF-->
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd<!--CRLF-->
http://www.springframework.org/schema/context<!--CRLF-->
http://www.springframework.org/schema/context/spring-context-3.0.xsd<!--CRLF-->
http://www.springframework.org/schema/util<!--CRLF-->
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!--CRLF-->
<!--CRLF-->
<context:component-scan base-package="com.hoo.*"><!--CRLF-->
<!-- 忽略这个类 -->
<!--CRLF-->
<context:exclude-filter type="assignable" expression="com.hoo.client.RESTClient"/><!--CRLF-->
</context:component-scan><!--CRLF-->
<!--CRLF-->
<!-- annotation的方法映射适配器 -->
<!--CRLF-->
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/><!--CRLF-->
<!--CRLF-->
<!-- xml视图,XStreamMarshaller,可以转换任何形式的java对象 -->
<!--CRLF-->
<bean name="xStreamMarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView"><!--CRLF-->
<property name="marshaller"><!--CRLF-->
<bean class="org.springframework.oxm.xstream.XStreamMarshaller"><!--CRLF-->
<!-- 为了初始化XStreamMarshaller,这个类会把我们接口中得到结果以XML文档形式展现出来 -->
<!--CRLF-->
<property name="autodetectAnnotations" value="true"/><!--CRLF-->
</bean><!--CRLF-->
</property><!--CRLF-->
</bean><!--CRLF-->
<!--CRLF-->
<!-- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 -->
<!--CRLF-->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"><!--CRLF-->
<property name="order" value="3"/><!--CRLF-->
</bean><!--CRLF-->
<!--CRLF-->
<!-- annotation默认的方法映射适配器 -->
<!--CRLF-->
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"><!--CRLF-->
<property name="order" value="1" /><!--CRLF-->
</bean><!--CRLF-->
<!--CRLF-->
</beans><!--CRLF-->
5、 启动后,可以看到index.jsp 没有出现异常或错误。那么当前SpringMVC的配置就成功了。
二、REST控制器实现
REST控制器主要完成CRUD操作,也就是对于http中的post、get、put、delete。
还有其他的操作,如head、options、trace。
具体代码:
package com.hoo.controller;
<!--CRLF-->
<!--CRLF-->
import org.springframework.stereotype.Controller;
<!--CRLF-->
import org.springframework.web.bind.annotation.PathVariable;
<!--CRLF-->
import org.springframework.web.bind.annotation.RequestMapping;
<!--CRLF-->
import org.springframework.web.bind.annotation.RequestMethod;
<!--CRLF-->
import org.springframework.web.servlet.ModelAndView;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>SpringMVC REST示例
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-6-9 上午11:34:08
<!--CRLF-->
* @file RESTController.java
<!--CRLF-->
* @package com.hoo.controller
<!--CRLF-->
* @project SpringRestWS
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@RequestMapping("/restful")
<!--CRLF-->
@Controller<!--CRLF-->
public class RESTController {<!--CRLF-->
<!--CRLF-->
@RequestMapping(value = "/show", method = RequestMethod.GET)
<!--CRLF-->
public ModelAndView show() {
<!--CRLF-->
System.out.println("show");
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("show method");
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
<!--CRLF-->
public ModelAndView getUserById(@PathVariable String id) {
<!--CRLF-->
System.out.println("getUserById-" + id);
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("getUserById method -" + id);
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@RequestMapping(value = "/add", method = RequestMethod.POST)
<!--CRLF-->
public ModelAndView addUser(String user) {
<!--CRLF-->
System.out.println("addUser-" + user);
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("addUser method -" + user);
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
<!--CRLF-->
public ModelAndView editUser(String user) {
<!--CRLF-->
System.out.println("editUser-" + user);
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("editUser method -" + user);
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
<!--CRLF-->
public ModelAndView removeUser(@PathVariable String id) {
<!--CRLF-->
System.out.println("removeUser-" + id);
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("removeUser method -" + id);
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
上面的方法对应的http操作:
/show -> get 查询<!--CRLF-->
/get/id -> get 查询<!--CRLF-->
/add -> post 添加<!--CRLF-->
/edit -> put 修改<!--CRLF-->
/remove/id -> delete 删除<!--CRLF-->
在这个方法中,就可以看到RESTful风格的url资源标识
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
<!--CRLF-->
public ModelAndView getUserById(@PathVariable String id) {
<!--CRLF-->
System.out.println("getUserById-" + id);
<!--CRLF-->
ModelAndView model = new ModelAndView("xStreamMarshallingView");<!--CRLF-->
model.addObject("getUserById method -" + id);
<!--CRLF-->
return model;
<!--CRLF-->
}<!--CRLF-->
value=”/get/{id}”就是url中包含get,并且带有id参数的get请求,就会执行这个方法。这个url在请求的时候,会通过Annotation的@PathVariable来将url中的id值设置到getUserById的参数中去。 ModelAndView返回的视图是xStreamMarshallingView是一个xml视图,执行当前请求后,会显示一篇xml文档。文档的内容是添加到model中的值。
三、利用RestTemplate调用REST资源
代码如下:
package com.hoo.client;
<!--CRLF-->
<!--CRLF-->
import org.springframework.beans.factory.annotation.Autowired;
<!--CRLF-->
import org.springframework.stereotype.Component;
<!--CRLF-->
import org.springframework.web.client.RestTemplate;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>RestTemplate调用REST资源
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-6-9 上午11:56:16
<!--CRLF-->
* @file RESTClient.java
<!--CRLF-->
* @package com.hoo.client
<!--CRLF-->
* @project SpringRestWS
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@Component<!--CRLF-->
public class RESTClient {<!--CRLF-->
<!--CRLF-->
@Autowired<!--CRLF-->
private RestTemplate template;
<!--CRLF-->
<!--CRLF-->
private final static String url = "http://localhost:8080/SpringRestWS/restful/";<!--CRLF-->
<!--CRLF-->
public String show() {
<!--CRLF-->
return template.getForObject(url + "show.do", String.class, new String[]{});<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public String getUserById(String id) {
<!--CRLF-->
return template.getForObject(url + "get/{id}.do", String.class, id);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public String addUser(String user) {
<!--CRLF-->
return template.postForObject(url + "add.do?user={user}", null, String.class, user);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public String editUser(String user) {
<!--CRLF-->
template.put(url + "edit.do?user={user}", null, user);
<!--CRLF-->
return user;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public String removeUser(String id) {
<!--CRLF-->
template.delete(url + "/remove/{id}.do", id);
<!--CRLF-->
return id;
<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
RestTemplate的getForObject完成get请求、postForObject完成post请求、put对应的完成put请求、delete完成delete请求;还有execute可以执行任何请求的方法,需要你设置RequestMethod来指定当前请求类型。
RestTemplate.getForObject(String url, Class<String> responseType, String... urlVariables)
参数url是http请求的地址,参数Class是请求响应返回后的数据的类型,最后一个参数是请求中需要设置的参数。
template.getForObject(url + "get/{id}.do", String.class, id);
如上面的参数是{id},返回的是一个string类型,设置的参数是id。最后执行该方法会返回一个String类型的结果。
下面建立一个测试类,完成对RESTClient的测试。代码如下:
package com.hoo.client;
<!--CRLF-->
<!--CRLF-->
import org.springframework.beans.factory.annotation.Autowired;
<!--CRLF-->
import org.springframework.test.context.ContextConfiguration;
<!--CRLF-->
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>RESTClient TEST
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-6-9 下午03:50:21
<!--CRLF-->
* @file RESTClientTest.java
<!--CRLF-->
* @package com.hoo.client
<!--CRLF-->
* @project SpringRestWS
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@ContextConfiguration("classpath:applicationContext-*.xml")
<!--CRLF-->
public class RESTClientTest extends AbstractJUnit38SpringContextTests {<!--CRLF-->
<!--CRLF-->
@Autowired<!--CRLF-->
private RESTClient client;
<!--CRLF-->
<!--CRLF-->
public void testShow() {<!--CRLF-->
System.out.println(client.show());<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public void testGetUserById() {<!--CRLF-->
System.out.println(client.getUserById("abc"));
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public void testAddUser() {<!--CRLF-->
System.out.println(client.addUser("jack"));
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public void testEditUser() {<!--CRLF-->
System.out.println(client.editUser("tom"));
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public void testRemoveUser() {<!--CRLF-->
System.out.println(client.removeUser("aabb"));
<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
我们需要在src目录下添加applicationContext-beans.xml完成对restTemplate的配置。restTemplate需要配置MessageConvert将返回的xml文档进行转换,解析成JavaObject。
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<beans xmlns="http://www.springframework.org/schema/beans"<!--CRLF-->
xmlns:context="http://www.springframework.org/schema/context"<!--CRLF-->
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<!--CRLF-->
xsi:schemaLocation="http://www.springframework.org/schema/beans<!--CRLF-->
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd<!--CRLF-->
http://www.springframework.org/schema/context<!--CRLF-->
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--CRLF-->
<!--CRLF-->
<context:component-scan base-package="com.hoo.*"/><!--CRLF-->
<!--CRLF-->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"><!--CRLF-->
<property name="messageConverters"><!--CRLF-->
<list><!--CRLF-->
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"><!--CRLF-->
<property name="marshaller" ref="xStreamMarshaller"/><!--CRLF-->
<property name="unmarshaller" ref="xStreamMarshaller"/><!--CRLF-->
</bean><!--CRLF-->
</list><!--CRLF-->
</property><!--CRLF-->
</bean><!--CRLF-->
<!--CRLF-->
<bean id="xStreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"><!--CRLF-->
<property name="annotatedClasses"><!--CRLF-->
<array><!--CRLF-->
</array><!--CRLF-->
</property><!--CRLF-->
</bean><!--CRLF-->
</beans><!--CRLF-->
上面配置了xStreamMarshaller是和RESTController中的ModelAndView的view对应的。因为那边是用xStreamMarshaller进行编组的,所以RestTemplate这边也需要用它来解组。RestTemplate还指出其他的MarshallingHttpMessageConverter;
相关推荐
首先我要说一个结论:RestTemplate请求结果异常是可以自定义处理的。在开始进行自定义的异常处理逻辑之前,我们有必要看一下异常处理的默认实现。也就是:为什么会产生上面小节提到的现象? ResponseErrorHandler...
RestTemplate实现服务间调用demo案例
ResponseEntity[]> rsp = restTemplate.getForEntity(url, byte[].class); System.out.println("文件下载请求结果状态码:" + rsp.getStatusCode()); // 将下载下来的文件内容保存到本地 String targetPath = ...
当某些接口超时、返回的数据有问题时需要对接口进行重试,但是有的接口需要重试三次,有的需要重试两次,有的不需要重试;有的返回连接超时才重试,...各种各样的场景,该源码实现了一个自定义定制化的重试RestTemplate
在RestTemplate发送请求得到非200状态结果的时候,间隔一定的时间再次发送n次请求。n次请求都失败之后,最后抛出HttpClientErrorException。 在开始本节代码之前,将上一节的RestTemplate自定义异常处理的代码注释掉...
RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层...
RestTemplate可以发送HTTP GET请求,经常使用到的方法有两个: getForObject() getForEntity() 二者的主要区别在于,getForObject()返回值是HTTP协议的响应体。getForEntity()返回的是ResponseEntity,Response...
SpringBoot系列之RestTemplate使用示例,博主之前经常对接一些接口,所以发现写一些http请求比较麻烦,学习springboot的过程知道可以用 RestTemplate来做http请求,RestTemplate 是 Spring Framework 框架封装的基于...
使用RestTemplate进行feignclient调用
精简客户端android环境jar包spring-android-core + spring-android-resttemplate +android.build.jar
Spring 3.0 RestTemplate
微服务springcloud:eureka整合gateway、RestTemplate和FeignClient
Riptide 是Spring RestTemplate的一个扩展,提供我们所说的客户端响应路由(client-side response routing)
采用httpclient方式和RestTemplate方式两种方式调用http或htpps请求的接口
RestTemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的,我们本小节就带着大家来看一下RestTemplate底层实现,及如何实现底层基础HTTP库的切换。
其实POST请求方法和GET请求方法上大同小异,RestTemplate的POST请求也包含两个主要方法: postForObject() postForEntity() 二者的主要区别在于,postForObject()返回值是HTTP协议的响应体。postForEntity()返回...
该示例结合Swagger生成在线API,MyBatis Plus快速分页查询、RestTemplate实现远程访问服务端接口等基于SpringBoot框架的demo示例,对大家学习SpringCloud打下良好基础
加密结果可能是:YWtaW46YWRtaW4=。 ...(注意这里使用Basic+空格+加密串) 服务器在收到这样的请求时,到达BasicAuthenticationFilter过滤器,将提取“authorization”的Header值,并使用用于验证用户身份的相同算法...
《深入理解Spring Cloud与微服务构建》学习笔记(十一)~使用RestTemplate和Ribbo消费服务
从Eureka到Ribbon、RestTemplate、Hystrix、Feign、zuul一个小例子