JAX-RS Entry 1: Basic

Source: Internet
Author: User
Tags getzip
Introduction

JAX-RS is a set of JAVA Implementation of the rest Service Specification, provides some annotation to a resource class, a pojojava class, encapsulated as web resources. Annotations include:

  • @ Path: indicates the relative path of the Resource class or method.
  • @ Get, @ put, @ post, @ Delete. The annotation method is the type of the HTTP request used.
  • @ Produces: indicates the mime media type returned.
  • @ Consumes: indicates the mime media type that can accept the request.
  • @ Pathparam, @ queryparam, @ headerparam, @ cookieparam, @ matrixparam, @ formparam, respectively indicate that the parameters of the method come from different locations of the HTTP request. For example, @ pathparam comes from the URL path, @ queryparam is the URL query parameter, @ headerparam is the header information of the HTTP request, and @ cookieparam is the cookie of the HTTP request.

The current JAX-RS implementation includes:

  • Apache cxf is an open-source Web Service Framework.
  • Jersey, a reference implementation of the JAX-RS provided by Sun.
  • Resteasy, JBoss implementation.
  • Restlet, developed by Jerome louvel and Dave pawson, is the earliest rest framework that appeared prior to JAX-RS.
  • Apache wink, an Apache Software Foundation incubator project, its service module implements JAX-RS specifications

(From: http://zh.wikipedia.org/wiki/JAX-RS)

 

Equipment

The tools used in this article include:

  • Eclipse-jee-Helios
  • Java-1.6.0_26
  • Apache -- tomcat-6.0.30
  • SoapUI-3.6

The external jar packages used are available (required and must be added to the Web container)

  • Neethi-3.0.2.jar
  • Jsr311-api-1.1.1.jar
  • Cxf-bundle-2.6.0.jar

The external jar packages used are available (optional, when and only treated as an independent application runtime)

  • Jetty-http-7.5.4.v20111024.jar
  • Jetty-io-7.5.4.v20111024.jar
  • Jetty-server-7.5.4.v20111024.jar
  • Jetty-util-7.5.4.v20111024.jar
  • Jetty-continuation-7.5.4.v20111024.jar
  • Wsdl4j-1.6.2.jar
Preparation

(Example from: oreilly-restful Java with JAX-RS (12-2009) (atticaworkflow)

 

Create a project

In order to proceed smoothly, create a dynamic web project on Eclipse first. After the project directory that conforms to the war structure is created automatically, the file can be easily exported as a war file, put the following jar package
/Webcontent/WEB-INF/libIn:

  • Neethi-3.0.2.jar
  • Jsr311-api-1.1.1.jar
  • Cxf-bundle-2.6.0.jar

In addition, in the project directory, create a new Lib folder to store the following optional jar packages:

 

  • Jetty-http-7.5.4.v20111024.jar
  • Jetty-io-7.5.4.v20111024.jar
  • Jetty-server-7.5.4.v20111024.jar
  • Jetty-util-7.5.4.v20111024.jar
  • Jetty-continuation-7.5.4.v20111024.jar
  • Wsdl4j-1.6.2.jar

The last step is to add all the nine jar files to the build path of the project, so that the project is ready.

 

Define Service

Here we need to implement a simple rest service for customer management, including:

  • Create Customer
  • View customer
  • Update customer

First, provide the corresponding service interfaces for these operations:

Java code
  1. Import java. Io. inputstream;
  2. Import javax. ws. Rs. consumes;
  3. Import javax. ws. Rs. Get;
  4. Import javax. ws. Rs. post;
  5. Import javax. ws. Rs. Put;
  6. Import javax. ws. Rs. path;
  7. Import javax. ws. Rs. pathparam;
  8. Import javax. ws. Rs. Produces;
  9. Import javax. ws. Rs. Core. response;
  10. Import javax. ws. Rs. Core. streamingoutput;
  11. @ Path ("/customers ")
  12. Public interface customerresource {
  13. @ Post
  14. @ Consumes ("application/XML ")
  15. Public Response createcustomer (inputstream is );
  16. @ Get
  17. @ Path ("{ID }")
  18. @ Produces ("application/XML ")
  19. Public streamingoutput getcustomer (@ pathparam ("ID") int ID );
  20. @ Put
  21. @ Path ("{ID }")
  22. @ Consumes ("application/XML ")
  23. Public void updatecustomer (@ pathparam ("ID") int ID, inputstream is );
  24. }

 

Surprisingly, this interface already contains all the key parts for achieving our stated goals:

  1. @ Path: Defines the service path. The top-level path of the entire service defined in the interface is"/Mers MERs
    ", The Service path corresponding to the method is the path value defined by the interface path plus method. If not defined, the interface path is used. For example, the Service path of getcustomer () is :"
    /Customers/{ID}". Therefore, the rest external service path isService context path/customers/
    Sub-Level directory,
  2. @ Post, @ get, @ put: Types of HTTP requests supported by the annotation method (refer to the above description)
  3. @ Produces, @ consumes: The request MIME type supported or returned by the annotation method.

We can see that the conditions for each method to be called are as follows:

  1. Createconsumer ():The request HTTP method is post, the request MIME type is application/XML, and the Request Path is:
    Context path/Mers MERs
  2. Getcustomer ():The HTTP Method of the request is get. The MIME type of the request is application/XML. The Request Path is:
    Context path/customers/{ID}
    Note: {ID} is the number of an existing (or nonexistent) customer.
  3. Updatecustomer ():The HTTP Method of the request is put; the MIME type of the request is application/XML; The Request Path:
    Context path/customers/{ID}
    Note: {ID} is the number of an existing (or nonexistent) customer.

A good implementation method is to separate the definition and implementation of the rest service. In this way, the code structure is concise and clear, and the implementation and modification of the service definition can be easily carried out in the future.

 

The following describes how to add an implementation:

Java code
  1. Public class customerresourceservice implements customerresource {
  2. Private Map <integer, Customer> customerdb = new concurrenthashmap <integer, Customer> ();
  3. Private atomicinteger idcounter = new atomicinteger ();
  4. Public Response createcustomer (inputstream is ){
  5. Customer customer = readcustomer (is );
  6. Customer. setid (idcounter. incrementandget ());
  7. Customerdb. Put (customer. GETID (), customer );
  8. System. Out. println ("created customer" + customer. GETID ());
  9. Return response. Created (URI. Create ("/Mers MERs/" + customer. GETID ()))
  10. . Build ();
  11. }
  12. Public streamingoutput getcustomer (int id ){
  13. Final customer = customerdb. Get (ID );
  14. If (customer = NULL ){
  15. Throw new webapplicationexception (response. Status. not_found );
  16. }
  17. Return new streamingoutput (){
  18. Public void write (outputstream) throws ioexception,
  19. Webapplicationexception {
  20. Outputcustomer (outputstream, customer );
  21. }
  22. };
  23. }
  24. Public void updatecustomer (int id, inputstream is ){
  25. Customer update = readcustomer (is );
  26. Customer current = customerdb. Get (ID );
  27. If (current = NULL)
  28. Throw new webapplicationexception (response. Status. not_found );
  29. Current. setfirstname (update. getfirstname ());
  30. Current. setlastname (update. getlastname ());
  31. Current. setstreet (update. getstreet ());
  32. Current. setstate (update. getstate ());
  33. Current. setzip (update. getzip ());
  34. Current. setcountry (update. getcountry ());
  35. }
  36. Protected void outputcustomer (outputstream OS, customer Cust)
  37. Throws ioexception {
  38. Printstream writer = new printstream (OS );
  39. Writer. println ("<customer ID = \" "+ Cust. GETID () +" \ "> ");
  40. Writer. println ("<first-name>" + Cust. getfirstname () + "</first-name> ");
  41. Writer. println ("<last-name>" + Cust. getlastname () + "</last-name> ");
  42. Writer. println ("<Street>" + Cust. getstreet () + "</street> ");
  43. Writer. println ("<city>" + Cust. getcity () + "</city> ");
  44. Writer. println ("<State>" + Cust. getstate () + "</State> ");
  45. Writer. println ("<zip>" + Cust. getzip () + "</zip> ");
  46. Writer. println ("<country>" + Cust. getcountry () + "</country> ");
  47. Writer. println ("</customer> ");
  48. }
  49. Protected customer readcustomer (inputstream is ){
  50. Try {
  51. Documentbuilder builder = documentbuilderfactory. newinstance ()
  52. . Newdocumentbuilder ();
  53. Document Doc = builder. parse (is );
  54. Element root = Doc. getdocumentelement ();
  55. Customer Cust = new customer ();
  56. If (root. getattribute ("ID ")! = NULL
  57. &&! Root. getattribute ("ID"). Trim (). Equals ("")){
  58. Cust. setid (integer. valueof (root. getattribute ("ID ")));
  59. }
  60. Nodelist nodes = root. getchildnodes ();
  61. For (INT I = 0; I <nodes. getlength (); I ++ ){
  62. Node item = nodes. item (I );
  63. If (! (Item instanceof element )){
  64. Continue;
  65. }
  66. Element element = (element) nodes. item (I );
  67. If (element. gettagname (). Equals ("first-name ")){
  68. Cust. setfirstname (element. gettextcontent ());
  69. } Else if (element. gettagname (). Equals ("last-name ")){
  70. Cust. setlastname (element. gettextcontent ());
  71. } Else if (element. gettagname (). Equals ("street ")){
  72. Cust. setstreet (element. gettextcontent ());
  73. } Else if (element. gettagname (). Equals ("city ")){
  74. Cust. setcity (element. gettextcontent ());
  75. } Else if (element. gettagname (). Equals ("state ")){
  76. Cust. setstate (element. gettextcontent ());
  77. } Else if (element. gettagname (). Equals ("Zip ")){
  78. Cust. setzip (element. gettextcontent ());
  79. } Else if (element. gettagname (). Equals ("country ")){
  80. Cust. setcountry (element. gettextcontent ());
  81. }
  82. }
  83. Return Cust;
  84. } Catch (exception e ){
  85. Throw new webapplicationexception (E, response. Status. bad_request );
  86. }
  87. }
  88. }

 

The implementation of these methods is very direct and I will not elaborate on it. However, note the following:

 

It is best not to include the definition of a service in the implementation, such as the @ path label and @ pathparam label. If you want to modify the definition, it is best to modify it in the interface; or, if you want to override an annotation of an interface method, the annotation definitions of all interfaces and methods must be rewritten, rather than modifying the changed ones.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.