使用Java的RESTful Web服务

REST代表“代表性状态转移”,由Roy Fielding于2000年在其论文“建筑风格和基于网络的软件体系结构设计”中首次提出。

REST是一种建筑风格。 HTTP是一种协议,其中包含一组REST体系结构约束。

REST基础


  • REST中的所有内容都被视为资源。
  • 每个资源都由URI标识。
  • 使用统一的接口。 使用POST,GET,PUT,DELETE操作处理资源,这些操作类似于创建,读取,更新和删除(CRUD)操作。
  • 无国籍。 每个请求都是一个独立的请求。 从客户端到服务器的每个请求必须包含理解该请求所需的所有信息。
  • 通信通过表示进行。 例如XML,JSON

RESTful Web服务

RESTful Web Services因其简单性而被Web上的大型服务提供商所接受,作为基于SOAP的Web Services的替代方案。 这篇文章将演示如何使用扩展JAX-RS API的Jersey框架创建RESTful Web服务和客户端。 使用Eclipse IDE和Java SE 6完成了示例。

    • 在Eclipse中,创建一个名为“ RESTfulWS”的新动态Web项目。

2013年11月7日的屏幕截图17-06-05

    • 此处下载Jersey zip捆绑包。 这些示例中使用的Jersey版本是1.17.1。 解压缩后,将有一个名为“ jersey-archive-1.17.1”的目录。 在其中找到lib目录。 从那里复制以下jar,并将其粘贴到项目中的WEB-INF-> lib文件夹中。 完成此操作后,也将这些jar添加到项目构建路径中。
      1. asm-3.1.jar
      2. jersey-client-1.17.1.jar
      3. jersey-core-1.17.1.jar
      4. jersey-server-1.17.1.jar
      5. jersey-servlet-1.17.1.jar
      6. jsr311-api-1.1.1.jar

2013-11-08 02-54-15的屏幕截图

2013-11-07 17-17-36的屏幕截图

    • 在您的项目中,在Java Resources-> src内创建一个名为“ com.eviac.blog.restws”的新包。 在其中创建一个新的Java类,称为“ UserInfo”。 还将给定的web.xml文件包含在WEB-INF文件夹中。
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>
    • 要运行该项目,请右键单击它,然后单击运行方式->在服务器上运行。
    • 在浏览器中执行以下URL,您将看到输出。
      http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

2013-11-08 02-04-07的屏幕截图

输出

2013-11-08 03-09-57的屏幕截图

    • 创建一个名为“ com.eviac.blog.restclient”的程序包。 在其中创建一个名为“ UserInfoClient”的Java类。
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);
 }
}
    • 运行客户端程序后,将获得以下输出。
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>

请享用!

参考: EVIAC博客上的JCG合作伙伴 Pavithra Siriwardena 提供的Java RESTful Web服务

翻译自: https://www.javacodegeeks.com/2013/11/restful-web-services-with-java.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值