前面介绍过spring的MVC结合不同的view显示不同的数据,如:结合json的view显示json、结合xml的view显示xml文档。那么这些数据除了在WebBrowser中用JavaScript来调用以外,还可以用远程服务器的Java程序、C#程序来调用。也就是说现在的程序不仅在BS中能调用,在CS中同样也能调用,不过你需要借助RestTemplate这个类来完成。RestTemplate有点类似于一个WebService客户端请求的模版,可以调用http请求的WebService,并将结果转换成相应的对象类型。至少你可以这样理解!

Blog:http://blog.csdn.net/IBM_hoojo

http://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/library

2、 需要jar包如下

3、 当前工程的web.xml配置

xml version="1.0" encoding="UTF-8"?>
<web-app version="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 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
    
    <servlet>
        <servlet-name>dispatcherservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/dispatcher.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    
    <servlet-mapping>
        <servlet-name>dispatcherservlet-name>
        <url-pattern>*.dourl-pattern>
    servlet-mapping>
    
    <welcome-file-list>
      <welcome-file>index.jspwelcome-file>
    welcome-file-list>
web-app>

4、 WEB-INF中的dispatcher.xml配置

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
 
    <context:component-scan base-package="com.hoo.*">
        
        <context:exclude-filter type="assignable" expression="com.hoo.client.RESTClient"/>
    context:component-scan>
 
    
    <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    
    
    <bean name="xStreamMarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView">
        <property name="marshaller">
            <bean class="org.springframework.oxm.xstream.XStreamMarshaller">  
                
                <property name="autodetectAnnotations" value="true"/>  
            bean>  
        property>
    bean>
        
    
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="3"/>
    bean>
 
    
    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="order" value="1" />
    bean>
    
beans>

5、 启动后,可以看到index.jsp 没有出现异常或错误。那么当前SpringMVC的配置就成功了。

二、REST控制器实现

REST控制器主要完成CRUD操作,也就是对于http中的post、get、put、delete。

还有其他的操作,如head、options、trace。

具体代码:

package com.hoo.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * function:SpringMVC REST示例
 * @author hoojo
 * @createDate 2011-6-9 上午11:34:08
 * @file RESTController.java
 * @package com.hoo.controller
 * @project SpringRestWS
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@RequestMapping("/restful")
@Controller
public class RESTController {
    
    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public ModelAndView show() {
        System.out.println("show");
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("show method");
        return model; 
    }
    
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public ModelAndView getUserById(@PathVariable String id) {
        System.out.println("getUserById-" + id);
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("getUserById method -" + id);
        return model; 
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView addUser(String user) {
        System.out.println("addUser-" + user);
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("addUser method -" + user);
        return model; 
    }
    
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public ModelAndView editUser(String user) {
        System.out.println("editUser-" + user);
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("editUser method -" + user);
        return model;
    }
    
    @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
    public ModelAndView removeUser(@PathVariable String id) {
        System.out.println("removeUser-" + id);
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("removeUser method -" + id);
        return model;
    }
}

上面的方法对应的http操作:

/show -> get 查询
/get/id -> get 查询
/add -> post 添加
/edit -> put 修改
/remove/id -> delete 删除

在这个方法中,就可以看到RESTful风格的url资源标识

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public ModelAndView getUserById(@PathVariable String id) {
    System.out.println("getUserById-" + id);
    ModelAndView model = new ModelAndView("xStreamMarshallingView");
    model.addObject("getUserById method -" + id);
    return model; 
}

value=”/get/{id}”就是url中包含get,并且带有id参数的get请求,就会执行这个方法。这个url在请求的时候,会通过Annotation的@PathVariable来将url中的id值设置到getUserById的参数中去。 ModelAndView返回的视图是xStreamMarshallingView是一个xml视图,执行当前请求后,会显示一篇xml文档。文档的内容是添加到model中的值。

三、利用RestTemplate调用REST资源

代码如下:

package com.hoo.client;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
 
/**
 * function:RestTemplate调用REST资源
 * @author hoojo
 * @createDate 2011-6-9 上午11:56:16
 * @file RESTClient.java
 * @package com.hoo.client
 * @project SpringRestWS
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@Component
public class RESTClient {
    
    @Autowired
    private RestTemplate template;
    
    private final static String url = "http://localhost:8080/SpringRestWS/restful/";
    
    public String show() {
        return template.getForObject(url + "show.do", String.class, new String[]{});
    }
    
    public String getUserById(String id) {
        return template.getForObject(url + "get/{id}.do", String.class, id); 
    }
    
    public String addUser(String user) {
        return template.postForObject(url + "add.do?user={user}", null, String.class, user);
    }
    
    public String editUser(String user) {
        template.put(url + "edit.do?user={user}", null, user);
        return user;
    }
    
    public String removeUser(String id) {
        template.delete(url + "/remove/{id}.do", id);
        return id;
    }
}

RestTemplate的getForObject完成get请求、postForObject完成post请求、put对应的完成put请求、delete完成delete请求;还有execute可以执行任何请求的方法,需要你设置RequestMethod来指定当前请求类型。

RestTemplate.getForObject(String url, Class responseType, String... urlVariables)

参数url是http请求的地址,参数Class是请求响应返回后的数据的类型,最后一个参数是请求中需要设置的参数。

template.getForObject(url + "get/{id}.do", String.class, id);

如上面的参数是{id},返回的是一个string类型,设置的参数是id。最后执行该方法会返回一个String类型的结果。

下面建立一个测试类,完成对RESTClient的测试。代码如下:

package com.hoo.client;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
 
/**
 * function:RESTClient TEST
 * @author hoojo
 * @createDate 2011-6-9 下午03:50:21
 * @file RESTClientTest.java
 * @package com.hoo.client
 * @project SpringRestWS
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@ContextConfiguration("classpath:applicationContext-*.xml")
public class RESTClientTest extends AbstractJUnit38SpringContextTests {
    
    @Autowired
    private RESTClient client;
    
    public void testShow() {
        System.out.println(client.show());
    }
    
    public void testGetUserById() {
        System.out.println(client.getUserById("abc"));
    }
    
    public void testAddUser() {
        System.out.println(client.addUser("jack"));
    }
    
    public void testEditUser() {
        System.out.println(client.editUser("tom"));
    }
    
    public void testRemoveUser() {
        System.out.println(client.removeUser("aabb"));
    }
}

我们需要在src目录下添加applicationContext-beans.xml完成对restTemplate的配置。restTemplate需要配置MessageConvert将返回的xml文档进行转换,解析成JavaObject。

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <context:component-scan base-package="com.hoo.*"/>
    
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                    <property name="marshaller" ref="xStreamMarshaller"/>
                    <property name="unmarshaller" ref="xStreamMarshaller"/>
                bean>
            list>
        property>
    bean>
    
    <bean id="xStreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
        <property name="annotatedClasses">
            <array>                
            array>
        property>
    bean>
beans>

上面配置了xStreamMarshaller是和RESTController中的ModelAndView的view对应的。因为那边是用xStreamMarshaller进行编组的,所以RestTemplate这边也需要用它来解组。RestTemplate还指出其他的MarshallingHttpMessageConverter;

(转载)spring RestTemplate用法详解的更多相关文章

  1. spring RestTemplate用法详解

    spring RestTemplate用法详解 spring 3.2.3 框架参考有说明 21.9 Accessing RESTful services on the Client

  2. [转载] C++ typedef 用法详解

    typedef的语法描述 在现实生活中,信息的概念可能是长度,数量和面积等.在C语言中,信息被抽象为int.float和 double等基本数据类型.从基本数据类型名称上,不能够看出其所代表的物理属性 ...

  3. (转载)spring mvc DispatcherServlet详解之一---处理请求深入解析

    要深入理解spring mvc的工作流程,就需要先了解spring mvc的架构: 从上图可以看到 前端控制器DispatcherServlet在其中起着主导作用,理解了DispatcherServl ...

  4. [转载]C# ListView用法详解

    一.ListView类 1.常用的基本属性: (1)FullRowSelect:设置是否行选择模式.(默认为false) 提示:只有在Details视图该属性才有意义. (2) GridLines:设 ...

  5. [转载]ssget 用法详解 by yxp

    总结得很好的ssget用法.....如此好文,必须转载. 原文地址: http://blog.csdn.net/yxp_xa/article/details/72229202 ssget 用法详解 b ...

  6. 转载 LayoutInflater的inflate函数用法详解

    http://www.open-open.com/lib/view/open1328837587484.html LayoutInflater的inflate函数用法详解 LayoutInflater ...

  7. [转帖]@RequestMapping 用法详解之地址映射(转)

    @RequestMapping 用法详解之地址映射(转) https://www.cnblogs.com/qq78292959/p/3760560.html 从csdn 发现的文章 然后csdn指向c ...

  8. @RequestMapping 用法详解之地址映射

    @RequestMapping 用法详解之地址映射 引言: 前段时间项目中用到了RESTful模式来开发程序,但是当用POST.PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没 ...

  9. Java 5 的新标准语法和用法详解集锦

    Java 5 的新标准语法和用法详解集锦 Java 5 的新标准语法和用法详解集锦 (需要在首选项-java-complier-compiler compliance level中设置为java5.0 ...

随机推荐

  1. NFS使用autofs自动挂载

    NFS自动挂载设置在/etc/fstab和/etc/rc.local可能挂载不成功,假如是服务端NFS宕机还可能导致客户端无法启动,可以使用autofs实现自动挂载 安装autofs yum -y i ...

  2. TOP100summit:【分享实录-美团点评】 业务快速升级发展背后的系统架构演进

    本篇文章内容来自2016年TOP100summit美团●大众点评高级技术专家,酒店后台研发组eHome团队负责人许关飞的案例分享.编辑:Cynthia 许关飞:美团●大众点评高级技术专家,酒店后台研发 ...

  3. java小tip

    //20181128 ·javaJDK源码在c盘java安装目录里jdk文件夹src.zip压缩包里 ·HashCode()返回的数可能是负数 ·内部类的优点:可以方便调用所在类的方法 ·接口中定义常 ...

  4. EM学习-思想和代码

    EM算法的简明实现 当然是教学用的简明实现了,这份实现是针对双硬币模型的. 双硬币模型 假设有两枚硬币A.B,以相同的概率随机选择一个硬币,进行如下的抛硬币实验:共做5次实验,每次实验独立的抛十次,结 ...

  5. arcgis二次开发遇到System.Runtime.InteropServices.COMException (0x80040228) :异常来自HRESULT:0x80040228

    出现此问题只需要在控件上拖入一个LicenseControl就可以了 参考资料:http://yaogu.blog.163.com/blog/static/1849990662012101283256 ...

  6. 2018/05/02 PHP 之错误与异常处理

    在学习中,越学习越觉得自己基础薄弱. 在平常工作中,对于某些错误处理感觉不知道怎么下手,于是决定重新再整理一下. 强烈推荐这篇文章,真的感觉学习到了很多. 部分引用::再谈PHP错误与异常处理 -- ...

  7. 洛谷P3237 米特运输 [HNOI2014] hash/二进制分解

    正解:hash/二进制分解 解题报告: 传送门! umm首先提取下题意趴QAQ 大概是说给一棵树,每个点有一个权值,要求修改一些点的权值,使得同一个父亲的儿子权值相同,且父亲的权值必须是所有儿子权值之 ...

  8. FTP主动模式和被动模式的区别(转)

    dd by zhj: 一般使用被动模式,在命令行下,被动模式的格式是:ftp -p (yinservice_env) ajian@ubuntu-desk:~$ ftp -pftp> 之前在用命令 ...

  9. python numpy初始化一个图像矩阵

    mask_all = np.zeros((256, 256), dtype='uint8')  单通道 mask_all_enlarge = np.zeros((256, 256, 3), dtype ...

  10. 批量查询"_mget"

    1.不同index的批量查询GET /_mget{ "docs":[{ "_index":"test_index1", "_typ ...