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