【转】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是没有状态的,发布和调用都非常的轻松容易. 下面写一 ...
随机推荐
- http请求参数中文乱码的问题
如题,A项目带参数发送请求到B项目.刚开始还好,但是发觉 参数带中文 就出现问题了,变成了?? 解决方法:发送中文参数前先做处理 request.getSession().removeAttribut ...
- spring-data-redis时效设置
本人转自http://hbxflihua.iteye.com/blog/2320584#bc2396403 spring目前在@Cacheable和@CacheEvict等注解上不支持缓存时效设置,只 ...
- html基本进阶知识【转】
inline和block的区别: 网页一般是两种元素组合起来的,一种是内联元素,也就是行内显示,加上width和height没效果.一种是区块元素,可以加上对应的width和height,通常使用在网 ...
- ubuntu常用
一.查看分区磁盘的速度命令 $ hdparm -Tt /dev/sda1 在终端打印出如下信息: /dev/sda1: Timing cached reads: MB in 2.00 seconds ...
- Hadoop生态组件的WebUI地址
================================Impala 相关================================ Impala的常用端口: jdbc/ODBC 端口: ...
- js 日期 相关
Js计算指定日期加上多少天.加多少月.加多少年的日期 function DateAdd(interval, number, date) { switch (interval) { case " ...
- 15个新鲜出炉的 Photoshop 文本效果教程
文本效果可能是 Photoshop 图形设计中最常用和最通用的技术之一.最重要的是你可以使用任何效果,风格或纹理来产生有趣的排版,越多人尝试过它并制作了一些精彩的教程.所以这篇文章旨在为您提供全面的 ...
- Idea运行web项目时,提示java.lang.ClassNotFoundException: com.mysql.jdbc.Driver解决方法
今天用 idea写了个工程.结果最后报错,错误信息如下: java.lang.ClassNotFoundException: com.mysql.jdbc.Driverat org.apache.ca ...
- 【省时的 IDEA 配置 】 JRebel Mybatis Problems Spring Auto-Scan
在 Java Web 开发中, 一般更新了 Java 文件后要手动重启 Tomcat 服务器, 才能生效, 浪费不少生命啊, 自从有了 JRebel 这神器的出现, 不论是更新 class 类还是更新 ...
- PySpider 爬虫系统
PySpider:一个国人编写的强大的网络爬虫系统并带有强大的WebUI.采用Python语言编写,分布式架构,支持多种数据库后端,强大的WebUI支持脚本编辑器,任务监视器,项目管理器以及结果查看器 ...