`
萧_瑟
  • 浏览: 158121 次
社区版块
存档分类
最新评论

restful webservice in springMVC Demo

    博客分类:
  • java
阅读更多

Maven restful webservice springMVC

 

服务端:

 

项目结构:

 

需要用到的jar包:

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.royal</groupId>
	<artifactId>restful_webservice</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>restful_webservice</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.0.RELEASE</version>  
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version> 
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>1.4.2</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
	</dependencies>
</project>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<display-name>restful web service</display-name>
    
  <!-- 
	  这里声明了名字为“restful”的Spring DispatcherServlet, 并匹配所有“/*”的“restful”servlet,
	  在Spring 3里,当它发现有 “restful” servlet时,它会自动在WEB-INF目录下寻找“restful-servlet.xml”
   -->
    <servlet>
        <servlet-name>restful</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>restful</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

注意:所声明的servlet-name一定要于自定义的xml文件名的头部部分相同,如果servlet-name为restful,则自定义的拦截的servlet xml文件的名称一定是restful-servlet.xml

 

 

自定义文件 restful-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:oxm="http://www.springframework.org/schema/oxm"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

	<!-- Spring会扫描com.royal包或他的子包的类来作为他的servlet组件 -->
    <context:component-scan base-package="com.royal" />

	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />

	<!-- 
		声明了一个bookXmlView bean 为了初始化XStreamMarshaller,
		这个类会把我们接口中得到结果以XML文档形式展现出来
	 -->
	<bean id="bookXmlView" 
		  class="org.springframework.web.servlet.view.xml.MarshallingView">
		<constructor-arg>
			<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
				<property name="autodetectAnnotations" value="true"/>
			</bean>
		</constructor-arg>
	</bean>
	
	<!-- 通过这个配置文档,我们声明我们的类和注释后,spring自己会照顾rest -->
</beans>

 

 

OK,如此之后,我们接下来再写com.royal下面的一些类文件了

 

首先,定义一个接口

RestfulService.java

package com.royal.application;

import java.util.List;

import com.royal.model.Author;

public interface RestfulService {
	
	public List<Author> loadAuthors();

}

 

其实现类  RestfulServiceImpl.java

package com.royal.application.facade;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.royal.application.RestfulService;
import com.royal.model.Author;

@Service("restfulService")
public class RestfulServiceImpl implements RestfulService {

	public List<Author> loadAuthors() {
		List<Author> authors = new ArrayList<Author>();
		Author a1 = new Author("royal");
		Author a2 = new Author("萧_瑟");
		authors.add(a1);
		authors.add(a2);
		return authors;
	}

}

 

补充上2个POJO类

 

Author.java

package com.royal.model;

/**
 *被@XStreamAlias()注释了,那么他们在XML文档下的显示别名就以其属性名显示 
 */

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("author")
public class Author {
	
	private String name;
	
	public Author(){
		
	}
	
	public Author(String name){
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

 

Book.java

package com.royal.model;

import java.io.Serializable;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("book")
public class Book implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private int id;
	private Author author;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Author getAuthor() {
		return author;
	}
	public void setAuthor(Author author) {
		this.author = author;
	}

}

 

最重要的是下面控制类:

 

RestfulController.java

package com.royal.controller;

/**
 * BookController class 被@Controller注释后,
 * 他会自动作为一个Spring MVC controller class。
 */

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.royal.application.RestfulService;
import com.royal.model.Author;

@Controller
public class RestfulController {

	@Autowired
	private RestfulService restfulService;

	/**
	 * @RequestMapping annotation(注释)会告诉Spring有关的URI, 比如“/xxx”。“method =
	 *                 RequestMethod.GET”代表以GET方式传递HTTP请求
	 * 
	 * @return
	 */
	@RequestMapping(value = "getBookAuthors", method = RequestMethod.GET)
	public ModelAndView getBookAuthors() {
		ModelAndView mav = null;
		List<Author> authors = restfulService.loadAuthors();

		/**
		 * 参数1:结果展现形式 参数2:模型对象的名称 参数3:模型对象结果
		 */
		mav = new ModelAndView("bookXmlView", BindingResult.MODEL_KEY_PREFIX
				+ "author", authors);

		return mav;
	}

}

 

最后,由于是maven项目,启动tomcat的时候记得勾上DevLoader Classpath 需要的类 和 General的一些填写信息


OK, 启动tomcat服务器。

 

浏览器中输入本地访问网址:http://localhost:8090/restful_webservice/services/getBookAuthors

 

注意这条访问的地址路径:

     其restful_webservice 指的就是项目名,General那边填写的信息;

     其services 就是web.xml中mapping url-pattern;

     其getBookAuthors 就是Controller下面的请求调用方法

 

最后访问结果:

 

================以下是客户端测试======================

 

客户端调用结果:

客户端项目结构:

model下的2个POJO类 Author、Book 和服务端是一样的 ,这样做主要用于层次结构的清晰,并无特殊含义。

 

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<display-name>restful web service client</display-name>
    
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		     classpath*:beans.xml
		</param-value>
	</context-param>
	
	 <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xmlns:tx="http://www.springframework.org/schema/tx" 
  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-2.5.xsd
                      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"  
  default-autowire="byName">
  
   <context:component-scan base-package="com.royal" />

	<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
		<property name="messageConverters">
			<list>
				<!-- We only have one message converter for the RestTemplate, namely the XStream Marshller -->
				<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
					<constructor-arg>
						<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
							
							<!-- Tell XStream to find the alias names in the following classes -->
							<property name="annotatedClasses">
								<list>
									<value>com.royal.model.Author</value>							
									<value>com.royal.model.Book</value>							
								</list>						
							</property>
						</bean>
					</constructor-arg>
				</bean>
			</list>
		</property>
	</bean>
	
	<bean id="restfulService" class="com.royal.application.facade.RestfulServiceImpl"/>
	
</beans>

 

 

RestfulService.java

package com.royal.application;

import java.util.List;

import com.royal.model.Author;

public interface RestfulService {
	
	public List<Author> loadAuthors();

}
 

 

RestfulServiceImpl.java

package com.royal.application.facade;

import java.util.List;

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

import com.royal.application.RestfulService;
import com.royal.model.Author;

@Component("restfulService")
public class RestfulServiceImpl implements RestfulService{

	@Autowired
	private RestTemplate restTemplate;
	
	private final static String serviceURL = "http://localhost:8090/restful_webservice/services/";
	
	public List<Author> loadAuthors() {
		return restTemplate.getForObject(serviceURL + "getBookAuthors", List.class);
	}

}
 

 

RestfulTest.java

package com.royal.client;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.royal.application.facade.RestfulServiceImpl;
import com.royal.model.Author;

public class RestfulTest {

	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
	RestfulServiceImpl restfulService = applicationContext.getBean("restfulService", RestfulServiceImpl.class);

	public static void main(String[] args) {
		new RestfulTest().launch();
	}

	public void launch() {
		if (restfulService != null) {
			List<Author> authorList = restfulService.loadAuthors();
			for (int i = 0; i < authorList.size(); i++) {
				Author author = authorList.get(i);
				System.out.println(author.getName());
			}
		} else {
			System.out.println("restfulService is null");
		}
	}

}
 

 

具体可下载附件。

 

同样的,因为采用的是maven项目构建,所以tomcat启动前请勾选DevLoader Classpath

需要勾选的就是一些spring启动时需要的一些jar

 

 

总结:

内容也许比较多,但是是为了更清楚的表达。

主要看关键

restful webservice 关键代码段

 

服务端:

       @Autowired
	private RestfulService restfulService;

	
	@RequestMapping(value = "getBookAuthors", method = RequestMethod.GET)
	public ModelAndView getBookAuthors() {
		ModelAndView mav = null;
		List<Author> authors = restfulService.loadAuthors();

		/**
		 * 参数1:结果展现形式 参数2:模型对象的名称 参数3:模型对象结果
		 */
		mav = new ModelAndView("bookXmlView", BindingResult.MODEL_KEY_PREFIX + "author", authors);

		return mav;
	}

 

 

客户端:

       @Autowired
	private RestTemplate restTemplate;
	
	private final static String serviceURL = "http://localhost:8080/restful_webservice/services/";
	
	public List<Author> loadAuthors() {
		return restTemplate.getForObject(serviceURL + "getBookAuthors", List.class);
	}

 

 

其余的便是配置!

 

服务端有个 restful-servlet.xml

客户端有个 beans.xml

 

 

 

参考:

      http://yangjizhong.iteye.com/blog/600540

      http://yangjizhong.iteye.com/blog/600680

 

 

  • 大小: 20.2 KB
  • 大小: 17.1 KB
  • 大小: 52.1 KB
  • 大小: 100.2 KB
  • 大小: 35.9 KB
  • 大小: 26.7 KB
  • 大小: 21.9 KB
  • 大小: 41.5 KB
分享到:
评论
1 楼 jssay 2012-05-28  
thanks for sharing, thanks.

相关推荐

    webservice -Restful的Demo

    通过这个"webservice - Restful的Demo",我们可以学习到RESTful如何使WebService变得更加简单、直观且高效。了解并掌握RESTful设计原则,能帮助我们构建更加优雅、易于维护的API,提升系统的可扩展性和互操作性。...

    SOAP webserivce 和 RESTful webservice 对比及区别

    基于REST的软件体系结构风格(Software Architecture Style)称之...按照REST原则设计的软件、体系结构,通常被称为“REST式的”(RESTful),在本文中以下称之为 RESTful Web服务,以便于和基于SOAP的Web服务区别。 

    SpringMVC demo 完整源码实例下载.zip

    在这个"SpringMVC demo 完整源码实例下载.zip"压缩包中,我们可以深入学习和理解SpringMVC的各种核心特性和实际应用。 首先,SpringMVC通过DispatcherServlet作为前端控制器,它负责接收HTTP请求,并根据请求的URL...

    RESTful WebService

    RESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状态的,发布和调用都非常的轻松容易。 下面写一个最简单的Hello World例子,以便对RESTful WebService有...

    Java RESTful WebService实战

    Java restful和webservice接口, WebService有两种方式,一是SOAP方式,二是REST方式。SOAP是基于XML的交互,WSDL也是一个XML文档,可以使用WSDL作为SOAP的描述文件;REST是基于HTTP协议的交互,支持JSON、XML等交互...

    RESTFul WebService

    在Web服务领域,RESTful已经成为构建可扩展、高性能和易于理解的API的标准方法。本资料集主要针对想要深入理解和实践RESTful风格的开发者。 首先,理解REST的核心概念至关重要。REST是一种架构风格,其核心思想是将...

    SpringMVC的Restful风格Demo

    在SpringMVC中实现RESTful风格,可以创建更加灵活、易于理解和维护的API。让我们深入探讨一下SpringMVC如何实现RESTful风格以及相关知识点。 首先,理解RESTful的基本原则至关重要。REST(Representational State ...

    基于SSM+CXF构建的RESTFul webservice

    使用cxf、spring构建的rest风格webservice,其他相关技术springmvc、mybatis、druid等。代码中使用的数据库为sybase,请根据实际环境更改,需修改pom中引用的数据库驱动,依照entity类的属性建对应表,并修改config....

    Jersey和Tomcat构建RESTful WebService

    Jersey和Tomcat构建RESTful WebService及其调用

    springMVC demo +jar包

    这个"springMVC demo +jar包"资源包含了一个Spring MVC的小型示例项目和必要的jar包,帮助初学者理解和实践Spring MVC框架的使用。 首先,让我们详细了解一下Spring MVC的核心概念: 1. **DispatcherServlet**:这...

    Spring Boot 实现Restful webservice服务端示例代码

    Spring Boot 实现Restful Webservice 服务端示例代码 Spring Boot 是一个基于 Java 的框架,用于快速构建生产级别的应用程序。它提供了许多有用的特性,如自动配置、嵌入式容器、生产准备等。下面,我们将探讨如何...

    CXF发布restful WebService的入门例子.pdf

    【CXF发布RESTful WebService】 RESTful WebService是一种基于HTTP协议的Web服务设计风格,它强调资源的表示和操作,通过HTTP方法(GET、POST、PUT、DELETE)来执行对资源的操作。Apache CXF是一个流行的开源Java...

    使用eclipse创建restful webservice 工程

    使用eclipse创建restful webservice 工程.d

    SOAP webserivce 和 RESTful webservice 对比及区别.pdf

    SOAP webserivce 和 RESTful webservice 对比及区别.pdfSOAP webserivce 和 RESTful webservice 对比及区别.pdf

    ssm-maven-cxf-oracle-RESTful WebService

    使用了cxf 同时实现了 RESTful WebService --项目启动后访问地址 http://localhost:8080/springMVC/services/rest/equipQuery/getUserById/1?_type=json 本人没有一一列明 xml json 以及post get请求 大家可以在...

    Restful WebService + Spring

    总的来说,"Restful WebService + Spring"的结合使得开发人员能够利用Spring的强大功能和RESTful的简洁设计原则,构建高效、可维护的Web服务。通过合理地组织资源、利用HTTP方法和状态码,以及借助Spring的自动化...

    rest soap cxf webservice maven springmvc

    例如,使用SpringMVC构建RESTful API,利用CXF支持SOAP服务,同时通过Maven管理项目依赖,确保开发环境的一致性。这种组合既满足了现代Web应用对轻量级、易用的需求,也能应对企业级应用中对复杂交互和安全性的要求...

    cxf集成Spring的restful WebService接口

    本教程将深入探讨如何在Spring环境中集成CXF以实现RESTful WebService接口。 首先,我们需要理解REST(Representational State Transfer)的概念。REST是一种软件架构风格,用于设计网络应用程序。它的核心思想是...

Global site tag (gtag.js) - Google Analytics