首页 > 其他分享 >spring RestTemplate用法详解

spring RestTemplate用法详解

时间:2023-07-31 10:38:18浏览次数:42  
标签:String spring RestTemplate public 详解 user ModelAndView model id


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

 


 

一、准备工作

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包如下

spring RestTemplate用法详解_javascript

 

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 [email protected]
 * @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 [email protected]
 * @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 [email protected]
 * @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;

标签:String,spring,RestTemplate,public,详解,user,ModelAndView,model,id
From: https://blog.51cto.com/nethub/6905696

相关文章

  • 使用Eclipse构建Maven的SpringMVC项目
    使用Eclipse构建Maven的SpringMVC项目      首先Eclipse需要安装Maven的插件,地址:http://m2eclipse.sonatype.org/sites/m2e。     用MyEclipse安装Maven插件,建出的Maven项目有些问题。一是,发布tomcat的时候resources总是不会被发布到tomcat下;二是,把WEB-INF下的cla......
  • 工业机器人坐标系详解(基于六轴串联机器人和SCARA机器人)
    工业机器人的坐标系机器人的坐标系是重中之重,它是理解机器人运动的基础。机器人所有运动的点位都是建立在坐标系的基础之上,所以如果坐标系不理解,那么就很难真实了解机器人是如何运动的。什么是坐标系?我们需要移动机器人来工作,但是如何让机器人移动?当然我们可以单独控制机器人的......
  • idea中SpringBoot项目module有红色下划线处理
    问题描述:项目打开时有的module会有红色下划线,点进去文件后又消失不见。项目启动时报错,无法启动。 解决方法:方法1.file->InvalidateCaches然后选择InvalidateandRestart(如果不管用的话可以√上ClearfilesystemcacheandLocalHistory再试一下,李粤说这个hisory挺......
  • 【SpringBoot】整合
    (知识目录)一、整合Junit使用@SpringBootTest注解可以定义测试类,要保证测试类在启动类在同一个包下,或者在启动类所处的类的子包下;如果不符合,要使用@SpringBootTest(classes=Demo3Application.class)下面通过service层和实现类模拟测试publicinterfaceUserService{......
  • 手把手带你入门 Spring Security!
    SpringSecurity是Spring家族中的一个安全管理框架,实际上,在SpringBoot出现之前,SpringSecurity就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是Shiro的天下。相对于Shiro,在SSM/SSH中整合SpringSecurity都是比较麻烦的操作,所以,SpringSecurity虽然功能比......
  • Spring中的设计模式详解
    Spring中的设计模式详解​JDK中用到了哪些设计模式?Spring中用到了哪些设计模式?这两个问题,在面试中比较常见。我在网上搜索了一下关于Spring中设计模式的讲解几乎都是千篇一律,而且大部分都年代久远。所以,花了几天时间自己总结了一下,由于我的个人能力有限,文中如有任何错误各......
  • SpringBatch
    SpringBatch配置数据库自动生成Spring:batch:jdbc:initialize-schema:never#always表示会进行初始化job:enabled:false#true程序启动的时候会进行调用jobfalse则不会调用Partition@Slf4jpublicclassPagePartiti......
  • day02_springboot综合案例
    day02_springboot综合案例订单操作查询所有订单查询所有订单流程查询订单,要把订单对应的产品也要查出来Orders实体类@DatapublicclassOrders{privateStringid;privateStringorderNum;@DateTimeFormat(pattern="yyyy-MM-ddHH:mm")privateDateorderTi......
  • day01_springboot综合案例
    springboot项目课程目标1.【掌握】SSM整合2.【掌握】使用SSM完成查询3.【理解】AdminLTE4.【理解】理解SSM综合案例表的结构springboot环境搭建搭建工程pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="htt......
  • 【微服务】springboot 多模块打包使用详解
    目录一、前言1.1为什么需要掌握多模块打包二、工程模块概述2.1前后端不分离2.2部署方式多样化2.3单模块向多模块演进三、单模块打包构建3.1环境准备3.1.1创建测试用的单模块工程3.1.2多环境配置文件3.1.3新增测试接口3.2pom配置详解3.2.1添加基础依赖3.2.2多环境配置3.2......