WebService implementation example based on rest mechanism (Java edition)

Source: Internet
Author: User
Tags representational state transfer java se

Rest is the abbreviation for the Representational state transfer (the general Chinese translation is the representational status transfer). 2000 Dr. Roy Fielding in his doctoral dissertation "Architectural Styles and the Design of network-based software Architectures" Rest is proposed in architecture and web-based software architecture design.

Rest is an architecture, and HTTP is a protocol that contains the properties of a rest schema.

Rest Basic Concepts

    • Everything in rest is considered a resource. Each resource has a URI and it corresponds.
    • Use the unified interface to process resources in rest. As with database crud operations (Create, Read, Update, and delete), rest resources can be processed with post, GET, put, and delete.
    • Each rest request is orphaned, and the request contains all the information needed. The rest service side does not store state.
    • Rest supports different communication data formats, such as XML, JSON.

RESTful Web Services

RESTful Web Services, which are widely used because of their simplicity, are much simpler than soap. This article focuses on how to create restful Web Services using the Jersey framework. The jersey framework implements the Jax-rs interface. The sample code in this article was written using Eclipse and Java SE 8.

A. New project: RESTFULWS, then create a RESTful Web service server

    • Create a Dynamic Web project in Eclipse, with the project name set to "RESTFULWS".
    • Download jersey (https://jersey.github.io/) from here. The sample code uses Jersey 1.19.1. First unzip the jersey to the "jersey-archive-1.19.1" folder. Then copy the jar file under the Lib folder into the project directory, Web-inf. lib. They are then added to the build path.
      1. Asm-3.1.jar
      2. Jersey-client-1.19.1.jar
      3. Jersey-core-1.19.1.jar
      4. Jersey-server-1.19.1.jar
      5. Jersey-servlet-1.19.1.jar
      6. Jsr311-api-1.1.1.jar
      7. Jersey-bundle-1.19.1.jar (download Http://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle separately)

Create the "Com.eviac.blog.restws" package in the project Java Resources, SRC, and create the "UserInfo" class in it.

Userinfo.java

 PackageCom.eviac.blog.restws;ImportJavax.ws.rs.GET;ImportJavax.ws.rs.Path;ImportJavax.ws.rs.PathParam;Importjavax.ws.rs.Produces;ImportJavax.ws.rs.core.MediaType;/** *  * @author  *  *///here @path defines the hierarchical path of the class. //Specifies the URI path of the resource class that provides the service. @Path ("Userinfoservice") Public classUserInfo {//@GET indicates that the method handles an HTTP GET request@GET//here @path defines the hierarchical path of the class. Specifies the URI path of the resource class that provides the service. @Path ("/name/{i}")    //@Produces defines the type of media that the resource class method generates. @Produces (mediatype.text_xml)//@PathParam injects a URI parameter value to an expression defined by @path.      PublicString UserName (@PathParam ("I") string i) {string name=i; return"<User>" + "<Name>" + Name + "</Name>" + "</User>"; } @GET @Path ("/age/{j}") @Produces (mediatype.text_xml) PublicString Userage (@PathParam ("J")    intj) {intAge =J; return"<User>" + "<Age>" + Age + "</Age>" + "</User>"; } @GET @Path ("/department/{k}") @Produces (mediatype.text_xml) PublicString userdepartment (@PathParam ("K") string k) {string userdepartment=K; return"<User>" + "<Department>" + userdepartment + "</Department>" + "</User>"; }}

Finally, copy the Web. XML to the Web-inf directory, and the Web. XML content is:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app id= "webapp_id" version= "2.5" 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 "><a href=" http://java.sun.com/xml/ Ns/javaee/web-app_2_5.xsd ">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" </a><display-name> Restfulws</display-name><servlet><servlet-name>jersey REST service</servlet-name>< Servlet-class>com.sun.jersey.spi.container.servlet.servletcontainer</servlet-class><init-param> <param-name>com.sun.jersey.config.property.packages</param-name><param-value> Com.eviac.blog.restws</param-value></init-param><load-on-startup>1</load-on-startup> </servlet><servlet-mapping><servlet-name>jersey REST service</servlet-name>< Url-pattern>/rest/*</url-pAttern></servlet-mapping></web-app> 
    • Copy this webservice-url to the browser address bar to run: HTTP://LOCALHOST:8080/RESTFULWS/REST/USERINFOSERVICE/NAME/LXJ

Second, a new project: Resttest, to create a client, using the previous project published WebService service interface

    • First create a standalone new project: Resttest (Create a Java project again).
    • This also requires a jar package under the Lib directory of the jersey framework. Unzip the jersey to the "jersey-archive-1.19.1" folder, and then copy the jar files under the Lib folder into the project directory, Web-inf. lib, or add them to the build path.

Asm-3.1.jar

Jersey-client-1.19.1.jar

Jersey-core-1.19.1.jar

Jersey-server-1.19.1.jar

Jersey-servlet-1.19.1.jar

Jsr311-api-1.1.1.jar

Jersey-bundle-1.19.1.jar (download Http://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle separately)

    • Create a "com.eviac.blog.restclient" package, and then new "Userinfoclient" class.

Userinfoclient.java

 Packagecom.eviac.blog.restclient;ImportJavax.ws.rs.core.MediaType;Importcom.sun.jersey.api.client.Client;ImportCom.sun.jersey.api.client.ClientResponse;ImportCom.sun.jersey.api.client.WebResource;ImportCom.sun.jersey.api.client.config.ClientConfig;ImportCom.sun.jersey.api.client.config.DefaultClientConfig;/** *  * @authorPavithra **/ Public classuserinfoclient { Public Static FinalString Base_uri = "Http://localhost:8080/RESTfulWS";  Public Static FinalString path_name = "/userinfoservice/name/";  Public Static FinalString path_age = "/userinfoservice/age/";  Public Static FinalString PATH_DEP = "/userinfoservice/department/"; /*** Returns the client request. Example: GET *http://localhost: 8080/restfulws/rest/userinfoservice/name/pavithra * Returns the request result status "OK". *      * @paramService *@return     */    Private StaticString Getclientresponse (WebResource Resource) {returnResource.accept (Mediatype.text_xml). Get (Clientresponse.class). toString (); }    /*** Return request result XML such as:<user><name>pavithra</name></user> * *@paramService *@return     */    Private StaticString GetResponse (WebResource Resource) {returnResource.accept (Mediatype.text_xml). Get (String.class); }     Public Static voidMain (string[] args) {String name= "Thunder"; intAge = 27; String Department= "China * * * Company"; ClientConfig Config=NewDefaultclientconfig (); Client Client=client.create (config); WebResource Resource=Client.resource (Base_uri); WebResource Nameresource= Resource.path ("rest"). Path (Path_name +name); System.out.println ("Client Response \ n" +Getclientresponse (Nameresource)); System.out.println ("Response \ n" + getResponse (nameresource) + "\ n"); WebResource Ageresource= Resource.path ("rest"). Path (Path_age +Age ); System.out.println ("Client Response \ n" +Getclientresponse (Ageresource)); System.out.println ("Response \ n" +GetResponse (Ageresource)); WebResource Departmentresource= Resource.path ("rest"). Path (PATH_DEP +department); System.out.println ("Client Response \ n" +Getclientresponse (Departmentresource)); System.out.println ("Response \ n" +GetResponse (Departmentresource)); }}
    • After you run the client program, you can see the following output:

WebService implementation example based on rest mechanism (Java edition)

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.