Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Rest Annotations

The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with HTTP-specific annotations to define resources and the actions that can be performed on those resources. Below lists some of the Java programming annotations that are defined by JAX-RS, with a description of how each is used. I will explain these annotation later.

@Path - The @Path annotation's value is a relative URI path indicating where the Java class will be hosted. It is imported from @javax.ws.rs.Path. The @Path annotation in JAX-RS is used to define a URI matching pattern for incoming HTTP requests. It can be placed upon a class or on one or more Java methods. For a Java class to be eligible to receive any HTTP requests, the class must be annotated with at least the @Path("/") expression. These types of classes are called JAX-RS root resources. For example if we write @Path("/customers") in class level, it means all request will come on this class for /users pattern.


@Path (value="/customers")
public class Customers {

}
 


@GET - @GET is the HTTP request method designator annotations. You can use them to bind Java methods in a root resource or subresource to HTTP request methods. HTTP GET requests are mapped to methods annotated with @GET annotation.


import javax.ws.rs.GET
@Path (value="/customers")
public class Customers {

@GET
public String getFirstMessage(){
return "This is my first Web RestService";
}
}
 


@POST - The POST HTTP method is used to add objects to a REST resource. You only need to add a parameter representing the object to your annotated method. The allowed return types are the same as @Get. In addition, POST requests should cause processing of the request body as a subordinate of the URL you are posting to.

In plain words:
POST /clients/
should not cause the resource at /clients/, itself, to be modified, but a resource whose URL starts with /clients/. For instance, it could append a new client to the list, with an id generated by the server.


@PUT - @PUT annotation is used to update existing record.A PUT request is used when you wish to create or update the resource identified by the URL. Unlike the former two requests this is not so widely used. Suppose on client request you are performing some action on the server and the state of the server has to be same in the next requests then you can go for PUT. For ex. When you upload a file for the first time a new file is created in the server and the state of the server has been changed. If you again try to upload the same file the old file has to be replaced by the new one instead of creating another one. Unlike POST, a client can issue this request safely two or more times because the state changed in the server should be same as in the first request. PUT is more linked with the update operation but that has not to be the case always.


@DELETE - As the name the delete annotation should be used to remove or delete something from the server. For ex. to delete a row from database table or remove a file from file-system etc. Sometimes people wrongly use GET or POST to do that but you are creating a service and want to say it is completely RESTful then you should use DELETE method for that.


@HEAD - The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.


@PathParam - @PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call. @PathParam can be used only on the following Java types:

  • All primitive types except char
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single Stringargument
  • Any class with the static method named valueOf(String) that accepts a single Stringargument
  • Any class with a constructor that takes a single String as a parameter

@QueryParam - @QueryParam denotes that the value of the Query Parameter with the corresponding name will be parsed, and if parsed correctly it will be available on the method argument denoted with@QueryParam. It is an annotation provided by the JAX-RS API. This annotation takes care of mapping a query parameter in a request to a method parameter.


@Consumes - The @Consumes annotation is used to specify the MIME media types of representations a resource can consume that were sent by the client.


@Produces - The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client, for example, "text/plain".


@Provider - The @Provider annotation is used for anything that is of interest to the JAX-RS runtime, such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity, and which can be built using Response.ResponseBuilder.


@CookieParam - Servers can store state information in cookies on the client, and can retrieve that information when the client makes its next request. Many web applications use cookies to set up a session between the client and the server. They also use cookies to remember identity and user preferences between requests. These cookie values are transmitted back and forth between the client and server via cookie headers. The @javax.ws.rs.CookieParam annotation allows you to inject cookies sent by a client request into your JAX-RS resource methods.


import javax.ws.rs.GET
@Path (value="/customers")
public class Customers {

@GET
public String getCustomer(@CookieParam("customerId") int custId){
}
}
 

The use of @CookieParam here makes the JAX-RS provider search all cookie headers for the customerId cookie value. It then converts it into an int and injects it into the custId parameter.


@HeaderParam - The @javax.ws.rs.HeaderParam annotation is used to inject HTTP request header values. For example, what if your application was interested in the web page that referred to or linked to your web service? You could access the HTTP Referer header using the @HeaderParam annotation:


import javax.ws.rs.GET
@Path (value="/customers")
public class Customers {

@GET
public String getCustomer(@HeaderParam("refer") int refer){
}
}
 

The @HeaderParam annotation is pulling the Referer header directly from the HTTP request and injecting it into the referer method parameter.


@FormParam - The @javax.ws.rs.FormParam annotation is used to access application/x-www-form-urlencoded request bodies. In other words, it's used to access individual entries posted by an HTML form document. For example, let's say we set up a form on our website to register new customers:


<FORM action="/customers" method="post ">
First name: <INPUT type="text" name="firstname">
Last name: <INPUT type="text" name="lastName">
<INPUT type="submit" value="SUBMIT"> 
<FORM>


import javax.ws.rs.GET
@Path (value="/customers")
public class Customers {

@GET
public String getCustomer(@FormParam("firstName") String firstName,
@FormParam("lastName") String lastName){
}
}
 

Here, we are injecting firstname and lastname from the HTML form into the Java parameters first and last. Form data is URL-encoded when it goes across the wire. When using @FormParam, JAX-RS will automatically decode the form entry's value before injecting it.


@MatrixParam - JAX-RS specification allows you to inject matrix parameter values directly through the @javax.ws.rs.MatrixParam annotation. Consider this URL

http://localhost:8012/projectName/rest/customers;firstName=customer1;lastName=customer2;

If you check in above URL, I am passing 2 parameters firstName=customer1 and lastName=customer2. One Parameter is separated from another with a semicolon, similarly you can pass any number of parameters. These type of parameters are called as Matrix Parameters. As per below example you can get these value from URL by using @MatrixParam annotations.


import javax.ws.rs.GET
@Path (value="/customers")
public class Customers {

@GET
public String getCustomer(@MatrixParam( "firstName") String firstName,
@MatrixParam("lastName") String lastName){
}
}
 


@BeanParam - The @BeanParam annotation is something new added in the JAX-RS 2.0 specification. It allows you to inject an application-specific class whose property methods or fields are annotated with any of the injection parameters. For more detail click here.


@Context - The @Context annotation enables you to access information about the application deployment context and the context of individual requests. This is imported from javax.ws.rs.core.Context. You can access information about HttpHeaders, Providers, Request, SecurityContext, UriInfo etc. from this annotation. I will explain this annotation with example later in this site.


@DefaultValue - Defines the default value of request meta-data that is bound using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if the corresponding meta-data is not present in the request. If the type of the annotated parameter is List, Set or SortedSet then the resulting collection will have a single entry mapped from the supplied default value.
If this annotation is not used and the corresponding meta-data is not present in the request, the value will be an empty collection for List, Set or SortedSet, null for other object types, and the Java-defined default for primitive types.


@Encode - The JAX-RS method parameters by default decode the values obtained from the request. @Encoded helps to keep values encoded if we want to decode ourselves. @Encoded can be applied at class level, method level and parameter level. @Encoded can be annotated at Class Level, Method Level, Parameter Level


     << Previous
Next >>