【转】RESTful Webservice创建
RESTful Web Services with Java
REST is an architectural style. HTTP is a protocol which contains the set of REST architectural constraints.
REST fundamentals
- Everything in REST is considered as a resource.
- Every resource is identified by an URI.
- Uses uniform interfaces. Resources are handled using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
- Be stateless. Every request is an independent request. Each request from client to server must contain all the information necessary to understand the request.
- Communications are done via representations. E.g. XML, JSON
RESTful Web Services
RESTful Web Services have embraced by large service providers across the web as an alternative to SOAP based Web Services due to its simplicity. This post will demonstrate how to create a RESTful Web Service and client using Jersey framework which extends JAX-RS API. Examples are done using Eclipse IDE and Java SE 6.
Creating RESTful Web Service
- In Eclipse, create a new dynamic web project called "RESTfulWS"

- Download Jersey zip bundle from here. Jersey version used in these examples is 1.17.1. Once you unzip it you'll have a directory called "jersey-archive-1.17.1". Inside it find the lib directory. Copy following jars from there and paste them inside WEB-INF -> lib folder in your project. Once you've done that, add those jars to your project build path as well.
- 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


- In your project, inside Java Resources -> src create a new package called "com.eviac.blog.restws". Inside it create a new java class called "UserInfo". Also include the given web.xml file inside WEB-INF folder.
UserInfo.java
- 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 here defines class level path. Identifies the URI path that
- // a resource class will serve requests for.
- @Path("UserInfoService")
- public class UserInfo {
- // @GET here defines, this method will method will process HTTP GET
- // requests.
- @GET
- // @Path here defines method level path. Identifies the URI path that a
- // resource class method will serve requests for.
- @Path("/name/{i}")
- // @Produces here defines the media type(s) that the methods
- // of a resource class can produce.
- @Produces(MediaType.TEXT_XML)
- // @PathParam injects the value of URI parameter that defined in @Path
- // expression, into the method.
- 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
- <?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" 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>
- To run the project, right click on it and click on run as ->run on server.
- Execute the following URL in your browser and you'll see the output.
- http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

output

Creating Client
- Create a package called "com.eviac.blog.restclient". Inside it create a java class called "UserInfoClient".
UserInfoClient.java
- 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));
- }
- /**
- * Returns client response.
- * e.g :
- * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
- * returned a response status of 200 OK
- *
- * @param service
- * @return
- */
- private static String getClientResponse(WebResource resource) {
- return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
- .toString();
- }
- /**
- * Returns the response as XML
- * e.g : <User><Name>Pavithra</Name></User>
- *
- * @param service
- * @return
- */
- private static String getResponse(WebResource resource) {
- return resource.accept(MediaType.TEXT_XML).get(String.class);
- }
- }
- Once you run the client program, you'll get following output.
- Client Response
- GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OK
- Response
- <User><Name>Pavithra</Name></User>
- Client Response
- GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK
- Response
- <User><Age>25</Age></User>
From: http://blog.eviac.com/2013/11/restful-web-services-with-java.html
【转】RESTful Webservice创建的更多相关文章
- Eclipse + Jersey 发布RESTful WebService(一)了解Maven和Jersey,创建一个WS项目(成功!)
一.下文中需要的资源地址汇总 Maven Apache Maven网站 http://maven.apache.org/ Maven下载地址: http://maven.apache.org/down ...
- SOAP Webservice和RESTful Webservice
http://blog.sina.com.cn/s/blog_493a845501012566.html REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的 ...
- RESTful WebService入门(转)
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/229206 REST ...
- CXF发布restful WebService的入门例子(服务器端)
研究了两天CXF对restful的支持. 现在,想实现一个以 http://localhost:9999/roomservice 为入口, http://localhost:9999/roomse ...
- RESTful Webservice (一) 概念
Representational State Transfer(表述性状态转移) RSET是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩 ...
- 使用CXF与Spring集成实现RESTFul WebService
以下引用与网络中!!! 一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存 ...
- RESTful WebService入门
RESTful WebService入门 RESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状 ...
- Web Service进阶(七)浅谈SOAP Webservice和RESTful Webservice
浅谈SOAP Webservice和RESTful Webservice REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性.RE ...
- RESTful WebService入门【转】
ESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状态的,发布和调用都非常的轻松容易. 下面写一 ...
随机推荐
- idea创建父子工程
第一步:创建一个新的父工程father:file—–>new—->project ,注意要选maven,Create from archetype不要勾选.next填写GroupId .A ...
- HTML第三耍 图像标签
复习一下第二耍: <!doctype html> <html> <head> <meta charset="utf-8"> < ...
- Python绘制wav文件音频图(静态)[matplotlib/wave]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 绘制波形图 plottingWaveform.py "&qu ...
- 复杂sql查询语句
视图也叫虚表 1.表中保存实际数据,视图保存从表中取出数据所使用的SELECT语句,视图也是一张表,之间区别是是否保存实际数据. 2.使用视图可以完成跨多表查询数据.可以将常用SELECT语句做成视图 ...
- 转--select/poll/epoll到底是什么一回事
面试题:说说select/poll/epoll的区别. 这是面试后台开发时的高频面试题,属于网络编程和IO那一块的知识.Android里面的Handler消息处理机制的底层实现就用到了epoll. 为 ...
- 自学python 2.
1.T or F 1>1 or 3<4 or 4>5 and 2>1 and 9>8 or 7<6 t not 2>1 and 3<4 or 4> ...
- python模块之collections random
collections 在内置数据类型(list, dict, tuple, set)的基础上,collections提供了几个额外的数据类型: Counter, deque, Orderdict, ...
- wx预览图片
wx.previewImage({ current: current, // 当前显示图片的http链接 urls: this.data.imgalist // 需要预览的图片http链接列表 }) ...
- 【四】Java虚拟机内存区域初识
一.线程独占区 1.程序计数器 程序计数器是一块处于线程独占区较小的内存空间,它可以看是当前线程所执行的字节码的行号指示器. 如果线程执行的是Java方法,这个计数器记录的是正在执行的虚拟机字节码 ...
- zookeeper windows伪集群搭建
1.下载zookeeper http://mirror.bit.edu.cn/apache/zookeeper/ 解压后,目录重命名为zookeeper1,进入 conf目录,把zoo_sample. ...