Build RESTful web service using Jersey
Server side
-----------------------------------------------------------
1) Dependencies:
jsr311.jar
jersey-core.jar
jersey-server.jar
asm.jar
2) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>HelloWorldApp</display-name>
<servlet>
<servlet-name>CMDA REST Web Services</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.zero.ws.rest.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- /resources/* or /* -->
<servlet-mapping>
<servlet-name>CMDA REST Web Services</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
3) ExchangeResource.java
import static com.zero.ws.rest.util.BaseUtils.deserializeDataObject;
import static com.zero.ws.rest.util.BaseUtils.serializeDataObject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.zero.ws.rest.domain.Exchange;
@Path("/exchange")
@Produces( { "application/xml" })
public class ExchangeResource {
@Context
UriInfo uriInfo;
@Context
Request request;
//application/octet-stream
String type = MediaType.APPLICATION_OCTET_STREAM;
@GET
@Path("/key/{exchCode}")
public Response getExchangeByKey(@PathParam("exchCode") String exchCode) {
if ((exchCode != null) && (exchCode.length() > 0)) {
Exchange exch = new Exchange();
exch.setName("Hello");
if (exch != null) {
byte[] buf = serializeDataObject(exch);
if ((buf != null) && (buf.length > 0)) {
return Response.ok(buf, "application/octet-stream").build();
}
}
}
return Response.noContent().build();
}
//By default, has a parameter byte[], don't need define @PathParam
//Can ignore it if don't declare this method parameter
@POST
@Path("/query/{exchCode}/{exchName}")
public Response query(byte[] data, @PathParam("exchCode") String exchCode, @PathParam("exchName") String exchName) {
Exchange exch = new Exchange();
exch.setExchCode(exchCode);
exch.setName(exchName);
System.out.println("Query: " + exchCode + ", " + exchName);
Exchange exch2 = (Exchange) deserializeDataObject(data, Exchange.class);
System.out.println("Orginal Exchange: " + exch2.getExchCode() + ", " + exch2.getName());
byte[] result = serializeDataObject(exch);
//Exchange exch2 = (Exchange) deserializeDataObject(data, Exchange.class);
//System.out.println("query: " + exch2.getExchCode() + ", " + exch2.getName());
return Response.ok(result, "application/octet-stream").build();
}
@POST
@Path("/create")
public Response createExchange(byte[] data) {
Exchange exch = (Exchange) deserializeDataObject(data, Exchange.class);
System.out.println("CREATE: " + exch.getExchCode());
return Response.ok(data, "application/octet-stream").build();
}
@POST
@Path("/get")
public Response getExchange(byte[] data) {
Exchange exch = (Exchange) deserializeDataObject(data, Exchange.class);
System.out.println("CREATE: " + exch.getExchCode());
return Response.ok(data, "application/octet-stream").build();
}
@POST
@Path("/update")
public Response updateExchange(byte[] data) {
Exchange exch = (Exchange) deserializeDataObject(data, Exchange.class);
System.out.println("UPDATE: " + exch.getExchCode());
return Response.ok(data, "application/octet-stream").build();
}
@POST
@Path("/delete")
public Response deleteExchange(@PathParam("exchange") String exchange) {
System.out.println("DELETE: " + exchange);
return Response.ok().build();
}
}
4) Deploy to Jetty
Dependencies:
geronimo-servlet_2.5_spec-1.2.jar
jetty-6.1.18.jar
jetty-util-6.1.18.jar
slf4j-api-1.5.6.jar
slf4j-jdk14-1.5.6.jar
/**
* Starts up a servlet container(Jetty) and adds the web application in web directory to it.
*
*
* @author louis
*/
public class Server {
private int port = 8088;
private String webDir = "web";
private String contextPath = "/RestHelloWorld";
protected Server() throws Exception {
System.out.println("Starting Server");
org.mortbay.jetty.Server server = new org.mortbay.jetty.Server();
//1) Set Connector
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
server.setConnectors(new Connector[] {connector});
//2) Set Context Path
WebAppContext webappcontext = new WebAppContext();
webappcontext.setContextPath(contextPath);
//3) Set War
webappcontext.setWar(webDir);
//4) Set handler
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
server.setHandler(handlers);
//5) Start
server.start();
System.out.println("Server ready...");
server.join();
}
public static void main(String args[]) throws Exception {
new Server();
}
}
Client side
-----------------------------------------------------------
1) Dependencies:
jsr311.jar
jersey-core.jar
jersey-server.jar
2) Test
import static com.zero.ws.rest.util.BaseUtils.deserializeDataObject;
import static com.zero.ws.rest.util.BaseUtils.serializeDataObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.zero.ws.rest.domain.Exchange;
public class TestExchange {
static String baseURL = "http://localhost:8088/RestHelloWorld/exchange";
public static void main(String[] args) {
new TestExchange().run();
Client client = Client.create();
WebResource webResource = null;
ClientResponse response = null;
// Query -> POST
webResource = client.resource(baseURL + "/query/002/Ellen");
Exchange newExchange = new Exchange();
newExchange.setExchCode("001");
newExchange.setName("New York");
byte[] data = serializeDataObject(newExchange);
response = webResource.post(ClientResponse.class, data);
System.out.println("Query response: " + response.getStatus());
byte[] byteArray = response.getEntity(byte[].class);
Exchange exch = deserializeDataObject(byteArray, Exchange.class);
System.out.println("query Exchange: " + exch.getExchCode() + ", " + exch.getName());
}
void run() {
Client client = Client.create();
WebResource webResource = null;
ClientResponse response = null;
// Read -> GET
webResource = client.resource(baseURL + "/key/ABC123");
response = webResource.get(ClientResponse.class);
byte[] byteArray = response.getEntity(byte[].class);
Exchange exch = deserializeDataObject(byteArray, Exchange.class);
System.out.println("Exchange name: " + exch.getName());
Exchange newExchange = new Exchange();
newExchange.setExchCode("NYSE");
newExchange.setName("New York Stock Exchange");
newExchange.setDescription("New York Stock Exchange 1");
byte[] newExchBin = serializeDataObject(newExchange);
// Create -> POST
webResource = client.resource(baseURL + "/create");
response = webResource.post(ClientResponse.class, newExchBin);
System.out.println("Create response: " + response.getStatus());
byteArray = response.getEntity(byte[].class);
exch = deserializeDataObject(byteArray, Exchange.class);
System.out.println("Create Exchange name: " + exch.getName());
// Read -> POST
webResource = client.resource(baseURL + "/get");
response = webResource.post(ClientResponse.class, newExchBin);
System.out.println("Read response: " + response.getStatus());
byteArray = response.getEntity(byte[].class);
exch = deserializeDataObject(byteArray, Exchange.class);
System.out.println("Read Exchange name: " + exch.getName());
// Update -> POST
webResource = client.resource(baseURL + "/update");
response = webResource.post(ClientResponse.class, newExchBin);
System.out.println("Update response: " + response.getStatus());
byteArray = response.getEntity(byte[].class);
exch = deserializeDataObject(byteArray, Exchange.class);
System.out.println("Update Exchange name: " + exch.getName());
// Delete -> POST
webResource = client.resource(baseURL + "/delete");
response = webResource.post(ClientResponse.class, newExchBin);
System.out.println("Delete response: " + response.getStatus());
}
}
分享到:
相关推荐
为了在Apache Tomcat服务器上部署Jersey创建的RESTful服务,开发者需要执行一系列步骤,如将Jersey库添加到项目的依赖中,配置web.xml来声明Jersey提供的Servlet,以及编写相应的资源类和方法。一旦这些步骤正确执行...
大神的Restful Web Service 详细介绍,Objectives By the end of this class, you should be able to: Give a working definition of RESTful Web Services actions, Enable a RESTful user in the SM operator ...
Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web 源代码Java Restful Web...
在现代的Web应用程序开发中,RESTful Web Service已经成为构建分布式系统和服务之间通信的重要方式。本文将深入探讨如何利用RESTful架构来实现转账业务,同时关注事务处理和并发控制这两个关键领域。 首先,让我们...
《Java RESTful Web Service实战》PDF版本下载
**JAX-RS方式的RESTful Web Service开发详解** RESTful Web Service是一种基于HTTP协议的、无状态的、客户端-服务器交互模式,它利用HTTP方法(GET、POST、PUT、DELETE等)来实现对资源的操作。JAX-RS是Java API ...
使用Java创建RESTful Web Service 在本文中,我们将讨论如何使用Java创建RESTful Web服务。REST(Representational State of Resource)是一种架构风格,它于2000年由Roy Fielding博士提出。RESTful Web服务是一种...
在"RESTful Web Service Demo"项目中,我们将探讨如何使用Java语言来创建这样的服务,并提供CURD(Create、Read、Update、Delete)操作。 首先,理解RESTful架构的关键概念: 1. 资源(Resource):在REST中,一切...
Jersey是Java平台上实现RESTful架构风格服务的一个流行框架,它基于JAX-RS(Java API for RESTful Web Services)标准。这篇博客文章“构建Restful Web服务-jersey”很可能是介绍如何使用Jersey来创建高效、可扩展的...
标题中的“2018最新谷歌浏览器RESTful Web Service离线版”指的是一个适用于谷歌浏览器的、用于开发和测试RESTful Web服务的工具,该工具的离线版本。RESTful Web Service是一种基于HTTP协议的软件架构风格,用于...
### Django RESTful Web Services: The Easiest Way to Build Python #### 一、概述与背景 本书主要聚焦于如何利用Python及其最受欢迎的Web框架Django来构建RESTful Web服务。随着互联网技术的发展,RESTful Web...
Restful web service cook book 中文版
《Java Restful Web Service实战》源代码.zip是一个包含与Java Restful Web Service开发相关的实践项目源码的压缩包。在本文中,我们将深入探讨Java Restful Web Service的关键概念、技术栈以及如何通过实际示例来...
Java RESTful Web Service是现代Web应用开发中的一个重要概念,它基于Representational State Transfer(表述性状态转移)架构原则,提供了一种轻量级、高效且易于理解和实现的接口设计方式。在本PDF教程《Java ...
restful web service cookbook
Java RESTful Web Service实战是Java开发领域中一个重要的实践教程,它主要涵盖了使用Java技术和RESTful架构风格来创建高效、可扩展的网络服务。REST(Representational State Transfer)是一种网络应用程序的设计...
### 解析Restful Web Service架构 #### 一、HTTP协议基础 HTTP(HyperText Transfer Protocol)是一种基于文档的协议,用于客户端与服务器之间的通信。它规定了一套标准的请求和响应格式,使得不同系统间的交互...
在本文中,我们将深入探讨如何使用SpringBoot框架与Jersey库整合来实现RESTful Web服务,并同时集成Spring MVC。这将使我们能够构建一个高效、灵活的后端系统,为客户端提供API接口。 首先,SpringBoot是Spring框架...