【转】RESTful Webservice创建

RESTful Web Services with Java

 
REST stands for REpresentational State Transfer, was first introduced by Roy Fielding in his thesis "Architectural Styles and the Design of Network-based Software Architectures" in year 2000. 

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.
      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
    • 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
  1.    
  2. package com.eviac.blog.restws;  
  3.   
  4. import javax.ws.rs.GET;  
  5. import javax.ws.rs.Path;  
  6. import javax.ws.rs.PathParam;  
  7. import javax.ws.rs.Produces;  
  8. import javax.ws.rs.core.MediaType;  
  9.   
  10. /** 
  11.  *  
  12.  * @author pavithra 
  13.  *  
  14.  */  
  15.   
  16. // @Path here defines class level path. Identifies the URI path that   
  17. // a resource class will serve requests for.  
  18. @Path("UserInfoService")  
  19. public class UserInfo {  
  20.   
  21.  // @GET here defines, this method will method will process HTTP GET  
  22.  // requests.  
  23.  @GET  
  24.  // @Path here defines method level path. Identifies the URI path that a  
  25.  // resource class method will serve requests for.  
  26.  @Path("/name/{i}")  
  27.  // @Produces here defines the media type(s) that the methods  
  28.  // of a resource class can produce.  
  29.  @Produces(MediaType.TEXT_XML)  
  30.  // @PathParam injects the value of URI parameter that defined in @Path  
  31.  // expression, into the method.  
  32.  public String userName(@PathParam("i") String i) {  
  33.   
  34.   String name = i;  
  35.   return "<User>" + "<Name>" + name + "</Name>" + "</User>";  
  36.  }  
  37.    
  38.  @GET   
  39.  @Path("/age/{j}")   
  40.  @Produces(MediaType.TEXT_XML)  
  41.  public String userAge(@PathParam("j"int j) {  
  42.   
  43.   int age = j;  
  44.   return "<User>" + "<Age>" + age + "</Age>" + "</User>";  
  45.  }  
  46. }  
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <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">    
  3.   <display-name>RESTfulWS</display-name>    
  4.   <servlet>    
  5.     <servlet-name>Jersey REST Service</servlet-name>    
  6.     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>    
  7.     <init-param>    
  8.       <param-name>com.sun.jersey.config.property.packages</param-name>    
  9.       <param-value>com.eviac.blog.restws</param-value>    
  10.     </init-param>    
  11.     <load-on-startup>1</load-on-startup>    
  12.   </servlet>    
  13.   <servlet-mapping>    
  14.     <servlet-name>Jersey REST Service</servlet-name>    
  15.     <url-pattern>/rest/*</url-pattern>    
  16.   </servlet-mapping>    
  17. </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.
      1. 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
  1. package com.eviac.blog.restclient;  
  2.   
  3. import javax.ws.rs.core.MediaType;  
  4.   
  5. import com.sun.jersey.api.client.Client;  
  6. import com.sun.jersey.api.client.ClientResponse;  
  7. import com.sun.jersey.api.client.WebResource;  
  8. import com.sun.jersey.api.client.config.ClientConfig;  
  9. import com.sun.jersey.api.client.config.DefaultClientConfig;  
  10.   
  11. /** 
  12.  *  
  13.  * @author pavithra 
  14.  *  
  15.  */  
  16. public class UserInfoClient {  
  17.   
  18.  public static final String BASE_URI = "http://localhost:8080/RESTfulWS";  
  19.  public static final String PATH_NAME = "/UserInfoService/name/";  
  20.  public static final String PATH_AGE = "/UserInfoService/age/";  
  21.   
  22.  public static void main(String[] args) {  
  23.   
  24.   String name = "Pavithra";  
  25.   int age = 25;  
  26.   
  27.   ClientConfig config = new DefaultClientConfig();  
  28.   Client client = Client.create(config);  
  29.   WebResource resource = client.resource(BASE_URI);  
  30.   
  31.   WebResource nameResource = resource.path("rest").path(PATH_NAME + name);  
  32.   System.out.println("Client Response \n"  
  33.     + getClientResponse(nameResource));  
  34.   System.out.println("Response \n" + getResponse(nameResource) + "\n\n");  
  35.   
  36.   WebResource ageResource = resource.path("rest").path(PATH_AGE + age);  
  37.   System.out.println("Client Response \n"  
  38.     + getClientResponse(ageResource));  
  39.   System.out.println("Response \n" + getResponse(ageResource));  
  40.  }  
  41.   
  42.  /** 
  43.   * Returns client response. 
  44.   * e.g :  
  45.   * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra  
  46.   * returned a response status of 200 OK 
  47.   * 
  48.   * @param service 
  49.   * @return 
  50.   */  
  51.  private static String getClientResponse(WebResource resource) {  
  52.   return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)  
  53.     .toString();  
  54.  }  
  55.   
  56.  /** 
  57.   * Returns the response as XML 
  58.   * e.g : <User><Name>Pavithra</Name></User>  
  59.   *  
  60.   * @param service 
  61.   * @return 
  62.   */  
  63.  private static String getResponse(WebResource resource) {  
  64.   return resource.accept(MediaType.TEXT_XML).get(String.class);  
  65.  }  
  66. }  
    • Once you run the client program, you'll get following output.
  1. Client Response   
  2. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a response status of 200 OK  
  3. Response   
  4. <User><Name>Pavithra</Name></User>  
  5.   
  6.   
  7. Client Response   
  8. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK  
  9. Response   
  10. <User><Age>25</Age></User>  
From: http://blog.eviac.com/2013/11/restful-web-services-with-java.html
 
中文版见: http://www.importnew.com/7336.html

转载于:https://www.cnblogs.com/justbeginning/p/3447164.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值