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. Git(使用码云)

    使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接的情况(原因你懂的). 如果我们希望体验Git飞一般的速度,可以使用国内的Git托管服务——码云(gitee.com) ...

  2. spring+springmvc+ibatis整合注解方式实例【转】

    源自-----> http://shaohan126448.iteye.com/blog/2033563 (1)web.xml文件(Tomcat使用) 服务器根据配置内容初始化spring框架, ...

  3. Oracle和Mysql的安装

    Oracle12C的安装:https://blog.csdn.net/qubeleyz/article/details/79451192 Mysql安装:

  4. JVM垃圾回收机制与内存回收

    暂时转于:https://blog.csdn.net/qq_27035123/article/details/72857739 垃圾回收机制 GC是垃圾回收机制,java中将内存管理交给垃圾回收机制, ...

  5. windows server 2008 r2 负载平衡 找不到主机 解决方案

    在C:\Windows\System32\drivers\etc文件夹中的host文件里手工将主机名WIN-********解析至IP 即可.

  6. AAndroid Studio的\drawable还是mipmap

    图片应该放在drawable文件夹下,而mipmap文件夹只适合放app icons

  7. MVC 自定义路由

    RouteConfig.cs 代码如下: public class RouteConfig { public static void RegisterRoutes(RouteCollection ro ...

  8. org.springframework.web.util.NestedServletException : Handler processing failed; nested exception is java.lang.StackOverflowError

    1 ,错误原因,循环冗余检查      result.setNearUsers(userList);            Page page = new Page();            pag ...

  9. python中requests的用法总结

    requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到.可以说,Requests 完全满足如今网络的需求 本文全部来源于官方文档 http://docs ...

  10. java json 转换

    1.直接输出: 2.字符串 通过eval转换输出,里面涉及到一个转义问题,还要注意eval的用法里面需要加"("+ + ")" 3.