spring-REST

1.controller类:

package com.mzj.practice.controller;
import org.apache.log4j.Logger;
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;

/**
 * Copyright (C),HANDPAY<br>
 *
 * SpringMVC REST
 *
 * @author muzhongjiang
 * @date 2014年10月26日
 */
@RequestMapping("/restful")
@Controller
public class RESTController {
    private final Logger LOG=Logger.getLogger(this.getClass());

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public ModelAndView show() {
        LOG.info("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) {
        LOG.info("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) {
        LOG.info("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) {
        LOG.info("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) {
        LOG.info("removeUser-" + id);
        ModelAndView model = new ModelAndView("xStreamMarshallingView");
        model.addObject("removeUser method -" + id);
        return model;
    }
}

2.spring rest 调用:

package com.mzj.practice.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Copyright (C),HANDPAY<br>
 *
 * RestTemplate调用REST资源
 *
 * RestTemplate的getForObject完成get请求、postForObject完成post请求、put对应的完成put请求、delete完成delete请求;<br>
 * 还有execute可以执行任何请求的方法, 需要你设置RequestMethod来指定当前请求类型。 <br>
 * RestTemplate.getForObject(String url, Class<String> responseType, String... urlVariables)
 * 参数url是http请求的地址,参数Class是请求响应返回后的数据的类型,最后一个参数是请求中需要设置的参数。<br>
 *
 * @author muzhongjiang
 * @date 2014年10月26日
 */
@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;
    }
}

3.配置spring-rest.xml:

<?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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

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

<!--RestTemplate需要配置MessageConvert将返回的xml文档进行转换,解析成JavaObject:  -->
    <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>

4.测试:

package com.mzj.practice.rest.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import com.mzj.practice.rest.RESTClient;

/**
 * Copyright (C),HANDPAY<br>
 *
 * RESTClient TEST
 *
 * @author muzhongjiang
 * @date 2014年10月26日
 */

@ContextConfiguration("classpath:applicationContext-*.xml")
public class RESTClientTest  extends AbstractJUnit4SpringContextTests{

    @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"));
    }
}
时间: 2025-01-03 00:27:41

spring-REST的相关文章

Spring事务管理(详解+实例)

写这篇博客之前我首先读了<Spring in action>,之后在网上看了一些关于Spring事务管理的文章,感觉都没有讲全,这里就将书上的和网上关于事务的知识总结一下,参考的文章如下: Spring事务机制详解 Spring事务配置的五种方式 Spring中的事务管理实例详解 1 初步理解 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必须是要么都执行要么都

SSM整合(spring,spirngmvc,mybatis)

整合思路   准备环境:导入jar包(spring mybatis  dbcp连接池  mysql驱动包 log4j) 工程结构: --------------------------- 1.  整合dao mybatis和spring进行整合   applicationContext-dao.xml 配置: 1.数据源 2.SqlSessionFactory 3.mapper扫描器 创建po以及mapper(通过逆向工程,这里不再演示) 针对综合查询mapper,一般情况会有关联查询,建议自定

Spring Boot 热部署

需要在pom.xml文件中加如下代码: 1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-devtools</artifactId> 5 <optional>true</optional> 6 </dependency> 7 </depe

Spring多线程

Spring是通过TaskExecutor任务执行器来实现多线程和并发编程的.使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor.而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync开启对异步的支持,并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务. 实例代码: (1)配置类 package com.lwh.highlight_spring4.ch3.taskexecutor; /**

Spring与JavaMail

JavaMail与Spring集成开发 spring框架集成JavaMail的主要包 2.mail.properties mail.smtp.host=smtp.163.com mail.smtp.auth=true mail.username=15511111111 mail.password=123 [email protected] 3.使用spring配置(applicationContext-mail.xml) <?xml version="1.0" encoding=

Spring Cloud ZooKeeper集成Feign的坑2,服务调用了一次后第二次调用就变成了500,错误:Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.n

错误如下: 2017-09-19 15:05:24.659 INFO 9986 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]56528192: startup date [Tue Sep 19 15:05:24 CST 2017]; root of context hierarchy 2017-09-19 15:05:24.858 INFO 9986 --

Spring rabbitMq 中 correlationId或CorrelationIdString 消费者获取为null的问题

问题 在用Spring boot 的 spring-boot-starter-amqp   快速启动 rabbitMq 是遇到了个坑 消费者端获取不到:correlationId或CorrelationIdString 问题产生的原因 correlationId 的在 spring rabbitmq 2.0 以后 byte方式会被放弃,所以 目前 代码中有些地方没有改过来,应该算一个BUG @SuppressWarnings("deprecation") public class De

Spring框架之Spring AOP

一.基于注解管理的AOP 1.Spring配置文件 <!-- 配置自动扫描包,自动扫描Bean组件,切面类 --> <context:component-scan base-package="com.zhoujian.spring.anno,com.zhoujian.spring.test"> <!-- <context:include-filter type="annotation" expression="org.a

Swagger+ springfox +Spring mvc

简介 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步.Swagger 让部署管理和使用功能强大的API从未如此简单.这一次我将从零开始搭建一个工程来演示如何在Spring mvc中整合Swagger生成Restful接口文档. 新建工程 我们新建一个Maven工程,并添加Web Facet,工程结构如下图所

Spring Aware

Spring的依赖注入最大亮点就是你所拥有的Bean对Spring容器的存在是没有意识的.即你可以将你的容器换成别的容器,如GOOGLE Guice,这时Bean之间的耦合度降低. 但是在实际的项目中,你不可避免的要用到Spring容器本身的资源,这时你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,这就是所谓的Spring Aware.其实Spring Aware本来就是Spring设计用来框架内部使用的,如果使用了Spring Aware,那么你的Bean其实