您的位置:首页 > 编程语言 > Java开发

RESTful Web Services in Spring 3

2014-03-11 16:27 411 查看
通过本文,我将介绍REST的特点,基本设计原则及其简单讲解,最后给出spring3.0下开发的RESTful Web Services 简单实例,其中许多内容是在网络上摘得,并通过自己理解写上的本人观点的博客,如有不同意见请指正。

REST(Representational State Transfer ),有中文翻译为"具象状态传输"(也有:"代表性状态传输")。是由 Roy Thomas Fielding博士 在2000年就读加州大学欧文分校期间在学术论文中提出的一个术语。他首次系统全面地阐述了REST的架构风格和设计思想。这篇论文是Web发展史上一篇非常重要的技术文献,他也为WEB架构的设计与评判奠定了理论基础。

注:附件里有论文的中文版,有兴趣的朋友可以下载看看。

REST 定义了一组体系架构原则,您可以根据这些,包括使用不同语言编写的客户端如何通过 HTTP 处理和传输资源状态。所以在事实上,REST 对 Web的影响非常大,由于其使用相当方便,已经普遍地取代了基于 SOAP 和 WSDL 的接口设计。在多年以后的今天,REST的主要框架已经开始雨后春笋般的出现。

个人理解:

(一) 首先REST只是一种风格,不是一种标准

(二) REST是以资源为中心

(三) REST充分利用或者说极端依赖HTTP协议

一.对于今天正在吸引如此多注意力的最纯粹形式的 REST Web 服务,其具体实现应该遵循以下基本设计原则

1.1.显式地使用不同的 HTTP 请求方法

1.2.无状态

1.3.公开目录结构式的 URI(通过逻辑URI定位资源)。

1.1.显式地使用不同的 HTTP 请求方法

我们在 Web 应用中处理来自客户端的请求时,通常只考虑 GET 和 POST 这两种 HTTP 请求方法。实际上,HTTP 还有 HEAD、PUT、DELETE 等请求方法。而在 REST 架构中,用不同的 HTTP 请求方法来处理对资源的 CRUD(创建、读取、更新和删除)操作:

若要在服务器上创建资源,应该使用 POST 方法。

若要检索某个资源,应该使用 GET 方法。

若要更改资源状态或对其进行更新,应该使用 PUT 方法。

若要删除某个资源,应该使用 DELETE 方法。

经过这样的一番扩展,我们对一个资源的 CRUD 操作就可以通过同一个 URI 完成了:

http://www.example.com/photo/logo(读取)

仍然保持为 [GET] http://www.example.com/photo/logo

http://www.example.com/photo/logo/create(创建)

改为 [POST] http://www.example.com/photo/logo

http://www.example.com/photo/logo/update(更新)

改为 [PUT] http://www.example.com/photo/logo

http://www.example.com/photo/logo/delete(删除)

改为 [DELETE] http://www.example.com/photo/logo

从而进一步规范了资源标识的使用。

通过 REST 架构,Web 应用程序可以用一致的接口(URI)暴露资源给外部世界,并对资源提供语义一致的操作服务。这对于以资源为中心的 Web 应用来说非常重要。

1.2.无状态

在 REST 的定义中,一个 Web 应用总是使用固定的 URI 向外部世界呈现一个资源。

它认为Web是由一系列的抽象资源组成,这些抽象的资源具有不同的具体表现形式。

譬如,定义一个资源为photo,含义是照片,它的表现形式可以是一个图片,也可以是一个.xml的文件,其中包含一些描述该照片的元素,或是一个html文件。 并且这些具体的表现可以分布在不同的物理位置上。

1.3.通过逻辑URI定位资源

实现这种级别的可用性的方法之一是定义目录结构式的 URI。

此类 URI 具有层次结构,其根为单个路径,从根开始分支的是公开服务的主要方面的子路径。 根据此定义,URI 并不只是斜杠分隔的字符串,而是具有在节点上连接在一起的下级和上级分支的树。 例如,在一个收集photo的相册中,您可能定义类似如下的结构化 URI 集合:

http://www.example.com/photo/topics/{topic}

如:http://www.example.com/photo/topics/home

根 / photo之下有一个 /topics 节点。 该节点之下有一系列主题名称,例如生日照片,聚会照片等等,每个主题名称指向某个讨论线。 在此结构中,只需在 {topic}输入某个内容即可容易地收集讨论线程。

在某些情况下,指向资源的路径尤其适合于目录式结构。 例如,以按日期进行组织的资源为例,这种资源非常适合于使用层次结构语法。

此示例非常直观,因为它基于规则:

http://www.example.com/photo/2010/02/22/{topic}

第一个路径片段是四个数字的年份,第二个路径片断是两个数字的月份,第三个片段是两个数字的日期。这就是我们追求的简单级别。 在语法的空隙中填入路径部分就大功告成了,因为存在用于组合 URI 的明确模式:

http://www.example.com/photo/{year}/{day}/{month}/{topic}

从而不需要我们去这样去传递信息:http://www.example.com/photo?year=xxxx&day=xxx$month=xxx&topic=xxxx

二.Restful web service的优点:

2.1 HTTP头中可见的统一接口和资源地址

通过对于HTTP Head 的解析,我们便可以了解到当前所请求的资源和请求的方式。

这样做对于一些代理服务器的设置,将带来很高的处理效率。

REST 系统中所有的动作和要访问的资源都可以从HTTP和URI中得到,这使得代理服务器、缓存服务器和网关很好地协调工作。而RPC模型的SOAP 要访问的资源仅从 URI无法得知,要调用的方法也无法从HTTP中得知,它们都隐藏在 SOAP 消息中。

同样的,在REST系统中的代理服务器还可以通过 HTTP 的动作 (GET 、 POST)来进行控制。

2.2 返回一般的XML格式内容

一般情况下,一个RESTful Web Service将比一个传统SOAP RPC Web Service占用更少的传输带宽。

Xml代码


POST/Order HTTP/1.1

Host:www.northwindtraders.com

Content-Type:text/xml

Content-Length:nnnn

<UpdatePO>

<orderID>098</orderID>

<customerNumber>999</customerNumber>

<item>89</item>

<quantity>3000</quantity>

</UpdatePO>

Xml代码


POST/Order HTTP/1.1

Host:www.northwindtraders.com

Content-Type:text/xml

Content-Length:nnnn

SOAPAction:"urn:northwindtraders.com:PO#UpdatePO"

<SOAP-ENV:Envelope

xmlns:xsi="http://www.3w.org/1999/XMLSchema/instance"

xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope"

xsi:schemaLocation="http://www.northwindtraders.com/schema/NPOSchema.xsd">

<SOAP-ENV:Body xsi:type="NorthwindBody">

<UpdatePO>

<orderID>098</orderID>

<customerNumber>999</customerNumber>

<item>89</item>

<quantity>3000</quantity>

</UpdatePO>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

2.3 安全机制

REST使用了简单有效的安全模型。REST中很容易隐藏某个资源,只需不发布它的URI;而在资源上也很容易使用一些安全策略,比如可以在每个 URI 针对 4个通用接口设置权限;再者,以资源为中心的 Web服务是防火墙友好的,因为 GET的 意思就是GET, PUT 的意思就是PUT,管理员可以通过堵塞非GET请求把资源设置为只读的,而现在的基于RPC 模型的 SOAP 一律工作在 HTTP 的 POST上。而使用 SOAP RPC模型,要访问的对象名称藏在方法的参数中,因此需要创建新的安全模型。

 三. 使用REST架构

  对于开发人员来说,关心的是如何使用REST架构,这里我们来简单谈谈这个问题。REST带来的不仅仅是一种崭新的架构,它更是带来一种全新的Web开发过程中的思维方式:通过URL来设计系统结构。REST是一套简单的设计原则、一种架构风格(或模式),不是一种具体的标准或架构。到今天REST有很多成功的使用案例,客户端调用也极其方便。

  目前宣称支持REST的Java框架包括以下这些:

  Restlet(http://www.restlet.org/

  Cetia4(https://cetia4.dev.java.net/

  Apache Axis2(http://http://ws.apache.org/axis2/

  sqlREST(http://sqlrest.sourceforge.net/

REST-art(http://rest-art.sourceforge.net/

下面是我通过Spring3.0写的一个很简单的REST举例。

依赖包请去http://www.springsource.com获得,Spring3.0于2009年12月发布,在GOOGLE中它的新特性被广泛提及的便是完整的springmvc rest支持。

另:Spring3已经完全采用Java5/6开发和编译构建,因此应该是不再支持Java1.4及更早版本了

说了些题外话,开始正题:

本实例是个简单的“article service”,分服务端和客户端,现在我先说下服务端开发:

注:服务端源代码请在附件里下载,是个maven建的eclipse工程。

web.xml:

Xml代码


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<display-name>Article Web Service</display-name>

<servlet>

<servlet-name>article</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>article</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>

</web-app>

这里声明了名字为“article”的Spring DispatcherServlet,并匹配所有“/*” 的“article”servlet,在Spring 3里,当它发现有 “article” servlet时,它会自动在WEB-INF目录下寻找“article”-servlet.xml,我现在贴出article-servlet.xml 内容:

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">

<context:component-scan base-package="com.informit.articleservice" />

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

<bean id="articleXmlView"

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>

</beans>

这里它做了几件事情:

1.Spring会扫描com.informit.articleservice包或他的子包来作为他的servlet组件

2.声明了一个articleXmlView bean 为了初始化XStreamMarshaller,这个类会把我们接口中得到结果以XML文档形式展现出来

通过这个配置文档,我们声明我们的类和注释后,spring自己会照顾rest,现在我们看下Spring MVC ArticleController class:

Java代码


package com.informit.articleservice;

import java.util.ArrayList;

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.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.servlet.ModelAndView;

import com.informit.articleservice.model.Article;

import com.informit.articleservice.model.Category;

import com.informit.articleservice.service.ArticleService;

@Controller

public class ArticleController {

@Autowired

private ArticleService articleService;

@RequestMapping(value = "/article/{category}/{id}", method = RequestMethod.GET)

public ModelAndView loadArticle(@PathVariable String category, @PathVariable int id,

@RequestParam(value = "mode", required = false) String mode) {

// Load the article based on the mode

Article article = null;

System.out.println("mode:" + mode);

if (mode != null && mode.equalsIgnoreCase("summary")) {

article = articleService.getArticleSummary(category, id);

} else {

article = articleService.getArticle(category, id);

}

// Create and return a ModelAndView that presents the article to the caller

ModelAndView mav = new ModelAndView("articleXmlView", BindingResult.MODEL_KEY_PREFIX + "article", article);

return mav;

}

@RequestMapping(value = "/article", method = RequestMethod.GET)

public ModelAndView loadArticleCategories() {

List<Category> categories = articleService.loadCategories();

ModelAndView mav = new ModelAndView("articleXmlView", BindingResult.MODEL_KEY_PREFIX + "category", categories);

return mav;

}

@RequestMapping(value = "/article", method = RequestMethod.DELETE)

public ModelAndView delArticleCategories() {

List<Category> categories = articleService.loadCategories();

System.out.println("delete oprate");

ModelAndView mav = new ModelAndView("articleXmlView", BindingResult.MODEL_KEY_PREFIX + "category", categories);

return mav;

}

@RequestMapping(value = "/addarticle", method = RequestMethod.POST)

public ModelAndView addArticleCategories(Category category) {

List<Category> categories = new ArrayList<Category>();

System.out.println(category.getName());

categories.add(category);

ModelAndView mav = new ModelAndView("articleXmlView", BindingResult.MODEL_KEY_PREFIX + "category", categories);

return mav;

}

@RequestMapping(value = "/addarticle/{name}", method = RequestMethod.POST)

public ModelAndView addArticleCategoriesForName(@PathVariable String name) {

List<Category> categories = new ArrayList<Category>();

Category category = new Category();

category.setName(name);

System.out.println(name);

categories.add(category);

ModelAndView mav = new ModelAndView("articleXmlView", BindingResult.MODEL_KEY_PREFIX + "category", categories);

return mav;

}

}

ArticleController class 被@Controller注释后,他会自动作为一个Spring MVC controller class,而@RequestMapping annotation(注释)会告诉Spring有关的URI,比如“/article”。“method = RequestMethod.GET”代表以GET方式传递HTTP请求,

我们可以通过http://localhost:8080/articleservice/article看下效果。

而"/article/{category}/{id}"代表{category}和{id}为传递进来的值作为URI,如通过http://localhost:8080/articleservice/article/kk/22来把相应的值传递进方法中,“@PathVariable String
category”即为category赋值,@RequestParam(value = "mode", required = false) String mode即可获得mode参数值,如:http://localhost:8080/articleservice/article/kk/22?mode=jizhong

然后处理逻辑后再ModelAndView中通过“articleXmlView”bean把loadArticle()方法的article对象或loadArticleCategories()方法的list返回

下面给出业务逻辑类:

Java代码


package com.informit.articleservice.service;

import java.util.List;

import com.informit.articleservice.model.Article;

import com.informit.articleservice.model.Category;

public interface ArticleService {

public Article getArticle(String category, int id);

public Article getArticleSummary(String category, int id);

public List<Category> loadCategories();

}

Java代码


package com.informit.articleservice.service;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import org.springframework.stereotype.Service;

import com.informit.articleservice.model.Article;

import com.informit.articleservice.model.Category;

@Service("articleService")

public class ArticleServiceImpl implements ArticleService {

@Override

public Article getArticle(String category, int id) {

return new Article(1, "My Article", "Steven Haines", new Date(), "A facinating article",

"Wow, aren't you enjoying this article?");

}

@Override

public Article getArticleSummary(String category, int id) {

return new Article(1, "My Article", "Steven Haines", new Date(), "A facinating article");

}

public List<Category> loadCategories() {

List<Category> categories = new ArrayList<Category>();

categories.add(new Category("fun"));

categories.add(new Category("work"));

return categories;

}

}

这里我列出使用的两个实体类:

Java代码


package com.informit.articleservice.model;

import java.io.Serializable;

import java.util.Date;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias( "article" )

public class Article implements Serializable

{

private static final long serialVersionUID = 1L;

private int id;

private String title;

private String author;

private Date publishDate;

private String summary;

private String body;

public Article()

{

}

public Article( int id, String title, String author, Date publishDate, String summary, String body )

{

this.id = id;

this.title = title;

this.author = author;

this.publishDate = publishDate;

this.summary = summary;

this.body = body;

}

public Article( int id, String title, String author, Date publishDate, String summary )

{

this.id = id;

this.title = title;

this.author = author;

this.publishDate = publishDate;

this.summary = summary;

}

public int getId()

{

return id;

}

public void setId( int id )

{

this.id = id;

}

public String getTitle()

{

return title;

}

public void setTitle( String title )

{

this.title = title;

}

public String getAuthor()

{

return author;

}

public void setAuthor( String author )

{

this.author = author;

}

public Date getPublishDate()

{

return publishDate;

}

public void setPublishDate( Date publishDate )

{

this.publishDate = publishDate;

}

public String getSummary()

{

return summary;

}

public void setSummary( String summary )

{

this.summary = summary;

}

public String getBody()

{

return body;

}

public void setBody( String body )

{

this.body = body;

}

}

Java代码


package com.informit.articleservice.model;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("category")

public class Category {

private String name;

public Category() {

}

public Category(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

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

至此,服务端配置就完成了,您可以通过连接:

http://localhost:8080/articleservice/article

http://localhost:8080/articleservice/article/fun/1

http://localhost:8080/articleservice/article/fun/1?mode=summary

因为篇幅,下一讲我将专门写客户端调用的工程: RESTful web services using Spring's RestTemplate class

注:附件里提供源码,有兴趣的朋友下载看吧

下篇的文章地址为:http://yangjizhong.iteye.com/admin/blogs/600680

========================================================

上一篇我主要发了RESTful Web Services in Spring 3的服务端代码,这里我准备写客户端的代码。

上篇得连接地址为:http://yangjizhong.iteye.com/blog/600540

开始本篇了:

注:附件里有源码,下载即可,依赖包请在spring网获得,谢谢。

applicationContext.xml:

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">

<context:component-scan base-package="com.informit.articleservice" />

<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.informit.articleservice.model.Article</value>

<value>com.informit.articleservice.model.Category</value>

</list>

</property>

</bean>

</constructor-arg>

</bean>

</list>

</property>

</bean>

</beans>

applicationContext.xml声明了一个bean,名restTemplate,implemented by org.springframework.web.client.RestTemplate,RestTemplate 类提供了一个setter来声明message converters,在这个属性我们提供一个包含一个简单bean的list:a MarshallingHttpMessageConverter,这是你的实体信息声明的地方

restTemplate bean声明后,ArticleClient 使用了restTemplate来调取ArticleService:

Java代码


package com.informit.articleservice.client;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import org.springframework.web.client.RestTemplate;

import com.informit.articleservice.model.Article;

import com.informit.articleservice.model.Category;

@Component("articleClient")

public class ArticleClient {

@Autowired

protected RestTemplate restTemplate;

private final static String articleServiceUrl = "http://localhost:8082/articleservice/";

@SuppressWarnings("unchecked")

public List<Category> getCategories() {

return restTemplate.getForObject(articleServiceUrl + "article", List.class);

}

public Article getArticle(String category, int id) {

return restTemplate.getForObject(articleServiceUrl + "article/{category}/{id}", Article.class, category, id);

}

@SuppressWarnings("unchecked")

public void delCategories() {

restTemplate.delete(articleServiceUrl + "article");

}

@SuppressWarnings("unchecked")

public List<Category> postCategories() {

Map<String, String> params = new HashMap<String, String>();

params.put("name", "jizhong");

return restTemplate.postForObject(articleServiceUrl + "addarticle/{name}", null, List.class, params);

}

}

在这里RestTemplate是自动加载的(auto-wired),你会注意到ArticleClient被加上了@Component annotation而且applicationContext.xml自动扫描com.informit.articleservice包或他的子包,因此当ArticleClient通过application context被loaded时,他会自动作为一个接口来实现RestTemplate实例

RestTemplate的相关使用的方法在文档中是这样写的:

delete(): deletes an object hosted by the web service

getForObject(): executes the HTTP GET command and returns the requested object

headForHeaders(): executes the HTTP HEAD command and returns the headers for the requested service

optionsForAllow(): executes the HTTP OPTIONS command and returns list of content types the the request service allows

postForLocation: executes the HTTP POST command and returns the location header value

postForObject(): executes the HTTP POST command and returns the object at the specified URL

put(): executes the HTTP PUT command and sends the specified object to the web service

execute(): provides fine grained control if one of the aforementioned methods does not suit your needs

接下来列出测试类:

Java代码


package com.informit.resttemplateexample;

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.informit.articleservice.client.ArticleClient;

import com.informit.articleservice.model.Category;

public class RestTemplateExample {

public static void main(String[] args) {

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

ArticleClient articleClient = applicationContext.getBean("articleClient", ArticleClient.class);

//get operate

// Article article = articleClient.getArticle("fun", 1);

// System.out.println("Article: " + article.getBody());

//

// List<Category> categories = articleClient.getCategories();

// for (Category category : categories) {

// System.out.println("Category: " + category);

// }

//delete operate

//articleClient.delCategories();

//post operate

List<Category> categories = articleClient.postCategories();

}

}

好了,然后本地跑一下就可以了,当然前提是一定把服务端跑起来哦....

注:详细代码在附件,JAR包还是自己下哈,终于写完了,有点累,但是有收获。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  web services