WebService implementation example based on rest mechanism (Java edition)

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

WebService implementation example based on rest mechanism (Java edition)

Rest is the abbreviation for the Representational state transfer (general Chinese translation is a descriptive status transfer). 2000 Roy Fielding in his Ph. D. thesis "Architectural Styles and the design of network-based Software architectures" Architecture and web-based Software architecture Design "Rest" is proposed.

Rest is an architecture, and HTTP is a protocol that contains rest architecture attributes.

The Rest Foundation concept everything in rest is considered a resource. Each resource has a URI and corresponds to it. Use a unified interface to process resources in rest. As with database crud operations (Create, Read, Update, and delete), you can use post, get, put, and delete to process rest resources. Each rest request is isolated, and the request contains all the information required. The rest service side does not store state. Rest supports different formats for communication data, such as XML, JSON.

RESTful Web Services

RESTful Web Services is widely used because of its simplicity, and it is simpler than soap . This article focuses on creating restful Web Services using the jersey framework . The jersey framework implements the Jax-rs interface. The sample code for this article is written using Eclipse and Java SE 6.

a new project: RESTFULWS, and then create a RESTful Web service server to create a "Dynamic Web project" in Eclipse with the project name set to "RESTFULWS".

Download jersey from here. The sample code uses Jersey 1.17.1. First unzip the jersey to the "jersey-archive-1.17.1" folder. Then copy the jar file inside the Lib folder to the Web-inf-> Lib of the engineering directory. They are then added to the build path. Asm-3.1.jar Jersey-client-1.17.1.jar Jersey-core-1.17.1.jar Jersey-server-1.17.1.jar Jersey-servlet-1.17.1.jar Jsr311-api-1.1.1.jar creates a "Com.eviac.blog.restws" package in the Engineering Java Resources-> SRC and creates a "UserInfo" class in it. Userinfo.java

Package Com.eviac.blog.restws;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;
Import Javax.ws.rs.PathParam;
Import javax.ws.rs.Produces;
Import Javax.ws.rs.core.MediaType;
//Specifies the URI path for the resource class to provide the service.
@Path ("Userinfoservice") public
class UserInfo {
	//@GET representation method handles HTTP GET requests
	@GET
	// Here @path defines the hierarchical path of the class. Specifies the URI path for the resource class to provide the service.
	@Path ("/name/{i}")
	//@Produces defines the type of media that the resource class method generates.
	@Produces (Mediatype.text_xml)
	//@PathParam inject the URI parameter values into the expression defined by the @path. Public
	string UserName (@PathParam ("I")
	string i) {
		string name = i;
		Return "<User>" + "<Name>" + Name + "</Name>" + "</User>";
	}

	@GET
	@Path ("/age/{j}")
	@Produces (mediatype.text_xml) public
	String userage (@PathParam ("J")
	Int j) {
		int age = j;
		Return "<User>" + "<Age>" + Age + "</Age>" + "</User>";
	}
Finally, the web.xml is copied 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.b log.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: Http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra

The output results are as follows:


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

First create a stand-alone new project:resttest (Create a second Java project).

This also requires a jar package under the Lib directory of the jersey framework. Unzip jersey to the "jersey-archive-1.17.1" folder, and then copy the jar files inside the Lib folder to the Web-inf-> Lib of the engineering directory or add them to build path. Asm-3.1.jar Jersey-client-1.17.1.jar Jersey-core-1.17.1.jar Jersey-server-1.17.1.jar Jersey-servlet-1.17.1.jar Jsr311-api-1.1.1.jar

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

Userinfoclient.java

Package com.eviac.blog.restclient;

Import Javax.ws.rs.core.MediaType;
Import com.sun.jersey.api.client.Client;
Import Com.sun.jersey.api.client.ClientResponse;
Import Com.sun.jersey.api.client.WebResource;
Import Com.sun.jersey.api.client.config.ClientConfig;

Import Com.sun.jersey.api.client.config.DefaultClientConfig; /** * * * @author Pavithra * */public class Userinfoclient {public static final String Base_uri = "Http://localhos
	T:8080/RESTFULWS ";
	public static final String path_name = "/userinfoservice/name/";

	public static final String path_age = "/userinfoservice/age/";
		public static void Main (string[] args) {String name = ' Pavithra ';

		int age = 25;
		ClientConfig config = new Defaultclientconfig ();
		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 \" + 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)); /** * Returns a client request.
	 For example: Get * Http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra * Returns the request result status "OK". * * @param service * @return/private static String Getclientresponse (WebResource Resource) {return resource.
	Accept (Mediatype.text_xml). Get (Clientresponse.class). toString ();
	 /** * Returns the request result XML such as:<user><name>pavithra</name></user> * * @param service * @return * * private static String GetResponse (WebResource Resource) {return resource.accept (mediatype.text_xml). Get (String.cla
	SS); }
}
After you run the client program, you can see the following output:
Client Response Get 
Http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra returned a Response Status of OK
Response 
<User><Name>Pavithra</Name></User>
 
Client Response Get 
Http://localhost:8080/RESTfulWS/rest/UserInfoService/age/25 returned a response status OK
Response 
<User><Age>25</Age></User>
Give it a try:

Original link: Eviac translation: importnew.com-chen Jie
Translation Links: http://www.importnew.com/7336.html

Related Article

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.