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. package com.eviac.blog.restws;
  2. import javax.ws.rs.GET;
  3. import javax.ws.rs.Path;
  4. import javax.ws.rs.PathParam;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.core.MediaType;
  7. /**
  8. *
  9. * @author pavithra
  10. *
  11. */
  12. // @Path here defines class level path. Identifies the URI path that
  13. // a resource class will serve requests for.
  14. @Path("UserInfoService")
  15. public class UserInfo {
  16. // @GET here defines, this method will method will process HTTP GET
  17. // requests.
  18. @GET
  19. // @Path here defines method level path. Identifies the URI path that a
  20. // resource class method will serve requests for.
  21. @Path("/name/{i}")
  22. // @Produces here defines the media type(s) that the methods
  23. // of a resource class can produce.
  24. @Produces(MediaType.TEXT_XML)
  25. // @PathParam injects the value of URI parameter that defined in @Path
  26. // expression, into the method.
  27. public String userName(@PathParam("i") String i) {
  28. String name = i;
  29. return "<User>" + "<Name>" + name + "</Name>" + "</User>";
  30. }
  31. @GET
  32. @Path("/age/{j}")
  33. @Produces(MediaType.TEXT_XML)
  34. public String userAge(@PathParam("j") int j) {
  35. int age = j;
  36. return "<User>" + "<Age>" + age + "</Age>" + "</User>";
  37. }
  38. }

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. import javax.ws.rs.core.MediaType;
  3. import com.sun.jersey.api.client.Client;
  4. import com.sun.jersey.api.client.ClientResponse;
  5. import com.sun.jersey.api.client.WebResource;
  6. import com.sun.jersey.api.client.config.ClientConfig;
  7. import com.sun.jersey.api.client.config.DefaultClientConfig;
  8. /**
  9. *
  10. * @author pavithra
  11. *
  12. */
  13. public class UserInfoClient {
  14. public static final String BASE_URI = "http://localhost:8080/RESTfulWS";
  15. public static final String PATH_NAME = "/UserInfoService/name/";
  16. public static final String PATH_AGE = "/UserInfoService/age/";
  17. public static void main(String[] args) {
  18. String name = "Pavithra";
  19. int age = 25;
  20. ClientConfig config = new DefaultClientConfig();
  21. Client client = Client.create(config);
  22. WebResource resource = client.resource(BASE_URI);
  23. WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
  24. System.out.println("Client Response \n"
  25. + getClientResponse(nameResource));
  26. System.out.println("Response \n" + getResponse(nameResource) + "\n\n");
  27. WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
  28. System.out.println("Client Response \n"
  29. + getClientResponse(ageResource));
  30. System.out.println("Response \n" + getResponse(ageResource));
  31. }
  32. /**
  33. * Returns client response.
  34. * e.g :
  35. * GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
  36. * returned a response status of 200 OK
  37. *
  38. * @param service
  39. * @return
  40. */
  41. private static String getClientResponse(WebResource resource) {
  42. return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
  43. .toString();
  44. }
  45. /**
  46. * Returns the response as XML
  47. * e.g : <User><Name>Pavithra</Name></User>
  48. *
  49. * @param service
  50. * @return
  51. */
  52. private static String getResponse(WebResource resource) {
  53. return resource.accept(MediaType.TEXT_XML).get(String.class);
  54. }
  55. }
    • 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. Client Response
  6. GET http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status of 200 OK
  7. Response
  8. <User><Age>25</Age></User>

From: http://blog.eviac.com/2013/11/restful-web-services-with-java.html

 

【转】RESTful Webservice创建的更多相关文章

  1. Eclipse + Jersey 发布RESTful WebService(一)了解Maven和Jersey,创建一个WS项目(成功!)

    一.下文中需要的资源地址汇总 Maven Apache Maven网站 http://maven.apache.org/ Maven下载地址: http://maven.apache.org/down ...

  2. SOAP Webservice和RESTful Webservice

    http://blog.sina.com.cn/s/blog_493a845501012566.html REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的 ...

  3. RESTful WebService入门(转)

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/229206 REST ...

  4. CXF发布restful WebService的入门例子(服务器端)

    研究了两天CXF对restful的支持.   现在,想实现一个以 http://localhost:9999/roomservice 为入口, http://localhost:9999/roomse ...

  5. RESTful Webservice (一) 概念

    Representational State Transfer(表述性状态转移) RSET是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩 ...

  6. 使用CXF与Spring集成实现RESTFul WebService

    以下引用与网络中!!!     一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存 ...

  7. RESTful WebService入门

    RESTful WebService入门   RESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状 ...

  8. Web Service进阶(七)浅谈SOAP Webservice和RESTful Webservice

    浅谈SOAP Webservice和RESTful Webservice REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性.RE ...

  9. RESTful WebService入门【转】

    ESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状态的,发布和调用都非常的轻松容易.   下面写一 ...

随机推荐

  1. .net中 登录 才能下载文件的方法 Response.WriteFile实现下载

    protected void Button2_Click(object sender, EventArgs e) { //可以在这里加是否登录的判断 string fileName = "c ...

  2. Linux下Maven私服Nexus3.x环境构建操作记录【转】

    Maven介绍Apache Maven是一个创新的软件项目管理和综合工具.Maven提供了一个基于项目对象模型(POM)文件的新概念来管理项目的构建,可以从一个中心资料片管理项目构建,报告和文件.Ma ...

  3. Spring Boot 启动:No active profile set, falling back to default profiles: default

    启动 Spring Boot 失败,但是没有出现多余的异常信息: 检查之后发现是依赖的问题(之前依赖的是 spring-boot-starter),修改即可: 方法二: pom.xml加上下面两个依赖 ...

  4. AJAX工作原理与缺点

    1.概念:什么是AJAXAJAX全称为“Asynchronous JavaScript and XML”(异步JavaScript和XML),是一种创建交互式网页应用的网页开发技术.2.为什么要使用他 ...

  5. 026、一张图搞懂docker(2019-01-21 周一)

    参考https://www.cnblogs.com/CloudMan6/p/6961665.html    

  6. 关于REST API设计的文章整理

    1. rest api uri设计的7个准则(1)uri末尾不需要出现斜杠/(2)在uri中使用斜杠/表达层级关系(3)在uri中可以使用连接符-提升可读性(4)在uri中不允许出现下划线字符_(5) ...

  7. 三、文件IO——系统调用(续)

    3.2.4 read 函数--- 读文件 read(由已打开的文件读取数据) #include<unistd.h> ssize_t read(int fd, void * buf, siz ...

  8. 第27月第6天 gcd timer

    1.gcd timer 因为如果不用GCD,编码需要注意以下三个细节: 1.必须保证有一个活跃的runloop. performSelector和scheduledTimerWithTimeInter ...

  9. 织梦自定义表单ajax提交范例

    function add_ajaxmessage(){ var dh = document.getElementById("tel"); //表单验证 if($("#te ...

  10. MIME 类型

    关于读音 为了防止大家出去丢人,我先示范一下,MIME应该独坐[maim],听起来就好像“男人”的英语法人一样. 浏览器和MIME的关系 浏览器依靠MIME类型解释网页. 每当浏览器请求一个web页面 ...