使用Java创建RESTful Web Service(转)
REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移)。2000年Roy Fielding博士在他的博士论文“Architectural Styles and the Design of Network-based Software Architectures”《体系结构与基于网络的软件架构设计》中提出了REST。
REST是一种体系结构。而HTTP是一种包含了REST架构属性的协议。
REST基础概念
- 在REST中所有东西都被看作资源。每一个资源都有一个URI和它对应。
- 在REST中使用统一接口处理资源。与数据库CRUD操作(Create、Read、Update 和 Delete)一样,可以用POST、GET、PUT和DELETE处理REST资源。
- 每个REST请求都是孤立的,请求中包含了所需的全部信息。REST服务端不存储状态。
- REST支持不同的通信数据格式,比如XML、JSON。
RESTful Web Services
RESTful Web Services因其简单性被广泛使用,它比SOAP要更简单。本文将重点介绍如何使用Jersey框架创建RESTful Web Services。Jersey框架实现了JAX-RS接口。本文示例代码使用Eclipse和Java SE 6编写。
创建RESTful Web Service服务端
- 在Eclipse中创建一个“dynamic web project”(动态web工程) ,项目名设为 “RESTfulWS”。

- 从这里下载Jersey。示例代码使用的是Jersey 1.17.1。首先解压Jersey到“jersey-archive-1.17.1”文件夹。接着将里面lib文件夹下的jar文件拷贝到工程目录的WEB-INF -> lib。然后将它们添加到build path。
- asm-3.1.jar
- jersey-client-1.17.1.jar
- jersey-core-1.17.1.jar
- jersey-server-1.17.1.jar
- jersey-servlet-1.17.1.jar
- jsr311-api-1.1.1.jar
- 在工程Java Resources -> src中创建“com.eviac.blog.restws”包,并在其中创建“UserInfo”类。最后把web.xml拷贝到WEB-INF目录下。


UserInfo.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package com.eviac.blog.restws;import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;/*** * @author pavithra* */// 这里@Path定义了类的层次路径。 // 指定了资源类提供服务的URI路径。@Path("UserInfoService")public class UserInfo {// @GET表示方法会处理HTTP GET请求@GET// 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。@Path("/name/{i}")// @Produces定义了资源类方法会生成的媒体类型。@Produces(MediaType.TEXT_XML)// @PathParam向@Path定义的表达式注入URI参数值。public String userName(@PathParam("i") String i) {String name = i;return "<User>" + "<Name>" + name + "</Name>" + "</User>";}@GET@Path("/age/{j}") @Produces(MediaType.TEXT_XML)public String userAge(@PathParam("j") int j) {int age = j;return "<User>" + "<Age>" + age + "</Age>" + "</User>";}} |
web.xml
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?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 <a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"</a> id="WebApp_ID" version="2.5"> <display-name>RESTfulWS</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.eviac.blog.restws</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> |
- 将此URL拷贝到浏览器地址栏中运行:
- http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

输出结果如下:

创建客户端
创建一个“com.eviac.blog.restclient”包,然后新建“UserInfoClient”类。
UserInfoClient.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package com.eviac.blog.restclient;import javax.ws.rs.core.MediaType;import com.sun.jersey.api.client.Client;import com.sun.jersey.api.client.ClientResponse;import com.sun.jersey.api.client.WebResource;import com.sun.jersey.api.client.config.ClientConfig;import com.sun.jersey.api.client.config.DefaultClientConfig;/*** * @author pavithra* */public class UserInfoClient {public static final String BASE_URI = "http://localhost:8080/RESTfulWS";public static final String PATH_NAME = "/UserInfoService/name/";public static final String PATH_AGE = "/UserInfoService/age/";public static void main(String[] args) {String name = "Pavithra";int age = 25;ClientConfig config = new DefaultClientConfig();Client client = Client.create(config);WebResource resource = client.resource(BASE_URI);WebResource nameResource = resource.path("rest").path(PATH_NAME + name);System.out.println("Client Response \n"+ getClientResponse(nameResource));System.out.println("Response \n" + getResponse(nameResource) + "\n\n");WebResource ageResource = resource.path("rest").path(PATH_AGE + age);System.out.println("Client Response \n"+ getClientResponse(ageResource));System.out.println("Response \n" + getResponse(ageResource));}/*** 返回客户端请求。* 例如:* GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra * 返回请求结果状态“200 OK”。** @param service* @return*/private static String getClientResponse(WebResource resource) {return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();}/*** 返回请求结果XML* 例如:<User><Name>Pavithra</Name></User> * * @param service* @return*/private static String getResponse(WebResource resource) {return resource.accept(MediaType.TEXT_XML).get(String.class);}} |
- 运行客户端程序后,可以看到以下输出:
|
1
2
3
4
5
6
7
8
9
|
Client Response GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OKResponse <User><Name>Pavithra</Name></User>Client Response GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OKResponse <User><Age>25</Age></User> |
试试吧 :)
http://www.importnew.com/7336.html
使用Java创建RESTful Web Service(转)的更多相关文章
- 使用Java创建RESTful Web Service
REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移).2000年Roy Fielding博士在他的博士论文“Architectural Sty ...
- spring3创建RESTFul Web Service
spring 3支持创建RESTFul Web Service,使用起来非常简单.不外乎一个@ResponseBody的问题. 例如:后台controller: 做一个JSP页面,使用ajax获取数据 ...
- 使用JAX-RS创建RESTful Web Service
guice resteasy http://www.cnblogs.com/ydxblog/p/7891224.html http://blog.csdn.net/withiter/article/d ...
- MEAN Stack:创建RESTful web service
本文在个人博客上的地址为URL,欢迎品尝. 前段时间做了DTREE项目中的前后端数据存储功能,在原有的ngController上进行HTTP请求,后端接受到请求后再存储到mongoDB上.现将学习所得 ...
- (转)接口自动化测试 – Java+TestNG 测试 Restful Web Service
本文主要介绍如何用Java针对Restful web service 做接口自动化测试(数据驱动),相比UI自动化,接口自动化稳定性可靠性高,实施难易程度低,做自动化性价比高.所用到的工具或类库有 T ...
- 使用 Spring 3 来创建 RESTful Web Services
来源于:https://www.ibm.com/developerworks/cn/web/wa-spring3webserv/ 在 Java™ 中,您可以使用以下几种方法来创建 RESTful We ...
- 使用 Spring 3 来创建 RESTful Web Services(转)
使用 Spring 3 来创建 RESTful Web Services 在 Java™ 中,您可以使用以下几种方法来创建 RESTful Web Service:使用 JSR 311(311)及其参 ...
- Spring 3 来创建 RESTful Web Services
Spring 3 创建 RESTful Web Services 在 Java™ 中,您可以使用以下几种方法来创建 RESTful Web Service:使用 JSR 311(311)及其参考实现 ...
- 怎样封装RESTful Web Service
所谓Web Service是一个平台独立的,低耦合的.自包括的.可编程的Web应用程序.有了Web Service异构系统之间就能够通过XML或JSON来交换数据,这样就能够用于开发分布式的互操作的应 ...
随机推荐
- Linux(CentOS或RadHat)下MySQL源码安装
安装环境: CentOS6.3 64位 软件: Mysql-5.6 所需包: gcc/g++ :MySQL 5.6开始,需要使用g++进行编译.cmake :MySQL 5.5开始,使用cmake进 ...
- Ubuntu中文输入法
这里是Ubuntu12.04,刚把系统语言设成英文,发现输入法没有了. 看看下面是如何找回来的吧. Ubuntu上的输入法主要有小小输入平台(支持拼音/二笔/五笔等),Fcitx,Ibus,Scim等 ...
- shell学习之常用命令总结
1.find命令 主要用途:主要用来做文件查找. 使用方法:查找文件的方式可以基于:文件名,文件时间属性,文件的所有者和组,文件权限属性,文件类型属性,文件大小,另外可以指定 查找目录的深度,排除指定 ...
- hibernate 数据关联一对多 3.1
一对多,多对一 (在多的一端存放一的外键) 但是在实体类中不需要创建这个外键 // 在一的一方创建Set集合 public class User { private Integer id; priva ...
- java学习之IO对象流
//注意对象类要打标记实现Serializable接口 package com.gh; import java.io.FileInputStream; import java.io.FileNotFo ...
- QT中QWidget类简介
一.详细描述 QWidget类是所有用户界面对象的基类.通俗的来讲,Qt基本上所有的UI类都是由QWidget继承出来的,而QWidget继承于QObject, 大家可以查阅Qt source 即可 ...
- 在Xcode中使用C++与Objective-C混编
有时候,出于性能或可移植性的考虑,需要在iOS项目中使用到C++. 假设我们用C++写了下面的People类: // // People.h // MixedWithCppDemo // // ...
- vs2013内置IISExpress相关问题
问题描述,以前做的程序迁移到vs2013后出现500.22问题. HTTP 错误 500.22 - Internal Server Error 检测到在集成的托管管道模式下不适用的 ASP.NET 设 ...
- SQL语句简单记录
SQL SERVER 新增列与默认值 alter table 表名 add 列明 bit default 0 not null 删除列(容易删除失败) alter table 表名 drop colu ...
- 内核printk打印等级
为了确认内核打印等级以及prink 参数对打印的分级,在led驱动初始化代码[以及exit出口]加入如下代码. 每次insmod .rmmod led模块时,根据打印等级的设置,得到不同的打印结果: ...