【转】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是没有状态的,发布和调用都非常的轻松容易. 下面写一 ...
随机推荐
- 【1】Java中double转BigDecimal的注意事项
项目遇到该问题 先上结论:不要直接用double变量作为构造BigDecimal的参数. 线上有这么一段Java代码逻辑: 1,接口传来一个JSON串,里面有个数字:57.3. 2,解析JSON并把这 ...
- Windows10开机自动运行批处理、脚本等的方法
方法/步骤: 一:打开我的电脑, 在地址栏输入:“C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”, 二,把自动运行批处理.脚 ...
- jsp查询修改
也是只帖代码....不讲解. 1.search.jsp <%@ page language="java" import="java.util.*" pag ...
- Task Asnyc 异常问题
/// <summary> /// async 异常捕获问题 /// </summary> /// <param name="context"> ...
- 使用TensorFlow遇到的若干问题
一.查看版本: 进入到Python的命令行状态后,可以在终端输入查询命令如下: import tensorflow tensorflow.__version__ 查询tensorflow安装路径为: ...
- ubuntu 18.04 安装 Redis
这篇博客写得不错,直接看这篇博客就OK了. https://wangxin1248.github.io/linux/2018/07/ubuntu18.04-install-redis.html
- Element-ui 中dialog的使用方法
<template> <div> <el-button type="text" @click="dialogFormVisible = tr ...
- IDEA Spring注入显示红色波浪线
- 同步&异步+阻塞&非阻塞(理解)
0 - 同步&异步 同步和异步关注的是消息通信机制. 0.1 - 同步 由“调用者”主动等待这个“调用”结果.即是,发出一个“调用”时,在没有得到结果之前,该“调用”不返回,一旦调用返回,则得 ...
- Setup ActorComponents
向头文件中添加一些组件 UStaticMeshComponent* MeshComp;//静态网格体组件 USphereComponent* SphereComp;//球体组件//用来接收物体碰撞信息 ...