Java craftsmanship: Creating RESTful Web Services/@Path @produces@pathparam__java with Java technology

Source: Internet
Author: User
Tags http post java web
Java tips: Creating RESTful Web Services/@Path @produces@pathparam with Java technology

Brief introduction

Jax-rs (JSR-311) is a specification for RESTful service capabilities in the Java EE environment. It provides a viable alternative to traditional SOAP-based Web services.

In this article, learn about the main components of Jax-rs. This article shows an example of how an enterprise can use the functionality within JAX-RS to expose employee contact information in a Restful way.

Background

Over the years, developers have used various tools to create RESTful services within their Java applications. Because of the simplicity of the REST architecture, the primary requirement-the ability to receive HTTP messages and headers-can be implemented by a simple Java Web container.

Java servlets are often used to develop RESTful applications. How to use the servlet does not have a fixed pattern. Typically, the servlet accepts the request and resolves the HTTP request URI itself to match the request to a known resource. For REST Services development, this simple servlet model is extended with a more formal API. However, since these APIs were developed on top of the servlet model, none of these APIs was developed as a formal standard.

As rest is increasingly being used as a schema, the Java Community Process (JCP) program includes formal support for rest in the future Java Enterprise Edition 6 release. JSR-311 has also been created and has the JAX-RS 1.0 specification, providing a new annotated way to develop RESTful services. Jax-rs annotations allow you to focus on your resources and data objects, compared to the servlet model. Also, you do not have to develop the communication layer (through the servlet).

Java Resources

JAX-RS has established a special language to describe resources, as represented by its programming model. There are five main entries: the root resource, the child resource, the resource method, the child resource method, and the child resource Locator.

Root Resource

The root resource is a Java class that is annotated by the @Path. @Path Note provides a value property that indicates the path to which this resource resides. The Value property can be a literal character, variable, or variable plus a custom regular expression. Listing 1 shows an example.
Listing 1. Jax-rs Root Resource

				
Package com.ibm.jaxrs.sample.organization;

Import Javax.ws.rs.Path;

@Path (value= "/contacts") public
class Contactsresource {
	...
}
					

Child Resources

A child resource is a Java class returned as a result of a subresource locator call. They are similar to root resources, except that they are not annotated by @Path because their paths are given by the child resource Locator. Child resources typically contain methods that are annotated by the HTTP request method indicator (designator) to serve this request. If they do not contain methods such as annotations, they will further resolve this resource processing request by assigning to the appropriate child resource locator.
Listing 2. Jax-rs Child Resources

				
Package com.ibm.jaxrs.sample.organization;

Import Javax.ws.rs.GET;

public class Department {
	

	
	@GET public
	String getdepartmentname () {
		...
	}
	

	
}}
					

Listing 2, shown above, shows the child resources returned by the Contactsresource.getcontactdepartment method. In this example, if an HTTP GET request is sent to the/contact/{contactname}/department path, the Getdepartmentname resource method within the Department child resource will process the request.

Resource methods

A resource method is a Java method that is bound to an HTTP method within a root resource or a child resource. Bindings are done through annotations such as @GET.
Listing 3. Jax-rs Resource Method

				
Package com.ibm.jaxrs.sample.organization;

Import java.util.List;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;

@Path (value= "/contacts") public
class Contactsresource {
	
	
	
	@GET public
	list<contactinfo> Getcontacts () {
		...}}
	


		        

In the example in Listing 3, HTTP get requests sent to the/contacts path are processed by the getcontacts () resource method.

Child Resource Method

A child resource method is very similar to a resource method; the only difference is that the child resource method is also annotated by the @Path, which further limits the choice of the method.
Listing 4. Jax-rs Sub Resource Method

				
Package com.ibm.jaxrs.sample.organization;

Import java.util.List;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;

@Path (value= "/contacts") public
class Contactsresource {
	
	@GET public
	list<contactinfo> Getcontacts () {
		...
	}
	
	
	
	@GET
	@Path (value= "/ids") public
	list<string> Getcontactids () {
		...
	}
	

}
					

In Listing 4, the HTTP get requests that are sent to the/contacts/ids path are processed by the Getcontactids () child resource method.

Child Resource Locator

A child resource locator is a way to further resolve the resources used to process a given request. They are very similar to child resource methods because they have a @Path annotation but do not have HTTP request method indicators, such as @GET annotations.
Listing 5. Jax-rs Child Resource Locator

				
Package com.ibm.jaxrs.sample.organization;

Import java.util.List;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;
Import Javax.ws.rs.PathParam;

@Path (value= "/contacts") public
class Contactsresource {
	
	@GET public
	list<contactinfo> Getcontactss () {
		...
	}
	
		@GET
	@Path (value= "/ids") public
	list<string> Getcontactids () {
		...
	}
	
	
	
	@Path (value= "/contact/{contactname}/department") public
	Department Getcontactdepartment (@PathParam (value=) ContactName ") 
		String ContactName) {
		...}}
	

}
		    

In the above example, any HTTP requests to the/contact/{contactname}/department path will be handled by the Getcontactdepartment child Resource Locator. The {ContactName} section indicates that the contact path part can be any valid URL value.

Comments

This section will explore some important annotations and their use. For a complete list of comments provided by the JAX-RS specification, you can refer to the JSR-311 links given in the Resources section of this article.

@Path

@Path annotations are used to describe the location of the root resource, child resource method, or child resource. Value values can contain text characters, variables, or variables that have custom regular expressions. The example in Listing 6 shows the main application of @Path annotations.
Listing 6. Use of @Path

				
Package com.ibm.jaxrs.sample.organization;

Import java.util.List;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;
Import Javax.ws.rs.PathParam;

@Path (value= "/contacts") public
class Contactsresource {

		
	@GET
	@Path (value= "/{emailaddress:.+@.+\\.[ a-z]+} ") Public
	ContactInfo getbyemailaddress (@PathParam (value=" EmailAddress ") 
		String EmailAddress) {
		...
	}
	
	@GET
	@Path (value= "/{lastname}") Public
	ContactInfo Getbylastname (@PathParam (value= "LastName") String LastName) {
		...}}
}
						

The annotation on the Contactsresource class indicates that all requests for the/contacts path will be processed by the Contactsresource root resource. The @Path comment on the getbyemailaddress indicates that any request sent to/contacts/{emailaddress} (where EmailAddress represents a regular expression). +@.+\\. [a-z]+] will be handled by Getbyemailaddress.

The @Path annotation on the Getbylastname method specifies all requests sent to the/contacts/{lastname} path (where LastName represents a valid URL that does not match the regular expression within the getbyemailaddress) Part) will be processed by the Getbylastname method.

@GET, @POST, @PUT, @DELETE, @HEAD

@GET, @POST, @PUT, @DELETE, and @HEAD are all HTTP request method indicator annotations. You can use them to bind Java methods and HTTP request methods within a root resource or child resource. HTTP GET requests are mapped to methods that are annotated by the @GET, and HTTP POST requests are mapped to methods that are @POST annotated, and so on. Users may also need to define their own custom HTTP request method indicators by using @HttpMethod annotations.
Listing 7. Custom HTTP Request Method Indicator annotation

				
Package com.ibm.jaxrs.sample.organization;

Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

Import Javax.ws.rs.HttpMethod;

@Retention (retentionpolicy.runtime)
@Target (Elementtype.method)
@HttpMethod (' get ') public
@ Interface Customget {

}
					

The above declaration defines the @CustomGET annotation. This comment will have the same semantic value as the @GET annotation and can be used in its place.

@Conumes and @Produces

@Consumes annotation represents a MIME type that a resource can accept. @Produces annotation represents the MIME type that a resource can return. These annotations can be found in resources, resource methods, child resource methods, child resource locators, or child resources.
Listing 8. @Consumes/@Produces

				
Package com.ibm.jaxrs.sample.organization;

Import java.util.List;
Import Javax.ws.rs.Consumes;
Import Javax.ws.rs.GET;
Import Javax.ws.rs.Path;
Import Javax.ws.rs.PathParam;
Import javax.ws.rs.Produces;

@Path (value= "/contacts") public
class Contactsresource {

		
	@GET
	@Path (value= "/{emailaddress:.+@.+\\.[ a-z]+} ")
	@Produces (value={" Text/xml "," Application/json "}) public
	ContactInfo getbyemailaddress (@ Pathparam (value= "EmailAddress") 
		String emailaddress) {
		...
	}
	
	@GET
	@Path (value= "/{lastname}")
	@Produces (value= "Text/xml") public
	ContactInfo Getbylastname (@ Pathparam (value= "LastName") String lastName) {
		...
	}
	
	@POST
	@Consumes (value={"Text/xml", "Application/json"}) public
	void Addcontactinfo (ContactInfo ContactInfo) {
		...}}
}

For these getbyemailaddress and Addcontactinfo methods, they can handle both Text/xml and Application/json. An accepted or returned resource represents an HTTP request header that will depend on the client settings. @Consumes comment matches the Content-type request header to determine whether the method can accept the contents of the given request.

In Listing 9, the Content-type header of Application/json plus the POST on the path/contacts indicates that the Addcontactinfo method within our Contactsresource class will be called to process the request.
Listing 9. Use of Content-type Head

				
Post/contacts http/1.1
Content-type:application/json
content-length:32

		    

Conversely, @Produces annotations are matched against the Accept request header to determine whether the client can handle the representation returned by the given method.
Listing 10. Use of Accept Head

				
get/contacts/johndoe@us.ibm.com http/1.1
Accept:application/json
			

In Listing 10, the GET request for/contacts/johndoe@us.ibm.com indicates that the Getbyemailaddress method will be invoked and that the returned format will be Application/json, not text/xml.

Providers

JAX-RS providers are application components that allow customization of run-time behavior in three critical areas: data binding, exception mapping, and context resolution (for example, providing a Jaxbcontext instance to the runtime). Each JAX-RS provider class must be commented by @Provider. The following example discusses two data binding providers Messagebodywriter and Messagebodyreader.

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.