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. Sqlserver远程过程调用失败

    这种情况一般是由于有高版本的SqlServer导致的,网上有删除Loaldb之类的建议,这样其实不太好,回头用高版本数据库的话还得装回来.其实可以通过计算机管理->服务和应用程序进行设置,用下面 ...

  2. Generic XXE Detection

    参考连接:https://www.christian-schneider.net/GenericXxeDetection.html In this article I present some tho ...

  3. 新浪某站CRLF Injection导致的安全问题

    CRLF攻击的一篇科普:新浪某站CRLF Injection导致的安全问题(转) 转:https://www.leavesongs.com/PENETRATION/Sina-CRLF-Injectio ...

  4. springboot06-swagger2 自动化api文档

    1.springboot 项目中添加swagger2依赖: <dependency> <groupId>org.springframework.boot</groupId ...

  5. Andrew NG 机器学习编程作业4 Octave

    问题描述:利用BP神经网络对识别阿拉伯数字(0-9) 训练数据集(training set)如下:一共有5000个训练实例(training instance),每个训练实例是一个400维特征的列向量 ...

  6. faster rcnn相关内容

    转自: https://zhuanlan.zhihu.com/p/31426458 faster rcnn的基本结构 Faster RCNN其实可以分为4个主要内容: Conv layers.作为一种 ...

  7. MySQL安装 8.0.15版本

    windows下MySQL 8.0.15的安装和设置 MySQL下载地址:https://dev.mysql.com/downloads/mysql/ 我的百度网盘下载(win64位):链接:http ...

  8. 洛谷P2251 【质量检测】

    无意中刷st表题看到的题目(抄模板),一看到题目,,,没想用st表,直接莫队?????跑起来也不是特别慢... 这里用flag数组记录出现次数,set维护最小值,用的时候直接取头部. 代码也很短 #i ...

  9. A Bayesian Approach to Deep Neural Network Adaptation with Applications to Robust Automatic Speech Recognition

    基于贝叶斯的深度神经网络自适应及其在鲁棒自动语音识别中的应用     直接贝叶斯DNN自适应 使用高斯先验对DNN进行MAP自适应 为何贝叶斯在模型自适应中很有用? 因为自适应问题可以视为后验估计问题 ...

  10. Censys

    Censys Censys持续监控互联网上所有可访问的服务器和设备,以便您可以实时搜索和分析它们,了解你的网络攻击面,发现新的威胁并评估其全球影响.从互联网领先的扫描仪ZMap的创造者来说,我们的使命 ...