Monday, August 12, 2013

Java WebService Tutorial - Part 12 ( Useful REST Annotations & Classes)


REST Annotations & Classes:

Hi, in this Section we will be discussing the different types of Annotations and some of the mostly used classes, provided by REST which can we use in our code.

First off, the most important Points we need to remember is:

REST is Web Service which performs all its Operation based upon the HTTP Methods. So it provides the following annotations.

@ GET
@POST
@PUT
@DELETE
@HEAD

If any one similar with the HTTP methods, they same they behave also here.

Some of the mostly used Annotations:

@Produces - This one we already discuss in our previous Sections, Any way it is used to produce a response to the User in based upon different MIME Types.( ex: text/html )

@Consumes - It is used to define what type of MIME or Inputs it will accepts from the Client .ex:  forms--URL--encoded.

@Context - It like the ServletContext in Servlet , it is the Jersey Framework context. It can used in many cases such as to get Header Parameters, Query parameters, Form Parameters etc.

Accessing Parameters in REST :

REST provides the following ways, the Param can be represented.

1.@PathParam
2.@QueryParam
3.@FormParam
4.@MatrixParam

1.@PathParam:

This annotation is used to get the Parameter specified in the URI using {} either from class level or Method Level.

Ex :CLASS LEVEL

@Path("/MyPath/{username}")
class MyPathResource
{
@GET
@Produces("text/plain")
public String getText(@PathParam("username"}String username)
{
return "UserName:"+username;
}
}

Access from URL :

Ayaz - Here taken as value for "username" and map to the Methods getText.Since getText does not have any path Associated with it the Jersey will automatically invokes this method.

Note: If there are more than one method specifies in the class with no path Annotation, then class will compile fine but the deployment will be fail.

EX: METHOD LEVEL

@Path("/MyPath/{username}")
class MyPathResource
{
@GET
@Produces("text/plain")
public String getText(@PathParam("username"}String username)
{
return "UserName:"+username;
}
@Path("/getText1/{text}")
@GET
@Produces("text/plain")
public String getText1(@PathParam("text"}String text)
{
return "Enter text:"+text;
}
}
Access from URL :

http://localhost:8080/MyPath/Ayaz  ---> Gives Output as UserName : Ayaz

http://localhost:8080/MyPath/getText1/HelloWorld  ---> Gives output as Enter text : HelloWorld

Note: If no value is pass for name  error will be thrown at runtime.


2. @Queryparam:

Queryparam is used to access the name and value pair enter in the URL using "?" .
It can be defined at class level and Method level; mostly it will be used in Method level. We will discuss Method level only.

Ex:

Here , name and age are the two Query parameters.

Ex:

    @Path("/MyMethod")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String Query(@QueryParam("name")String name ,
    @QueryParam("age")String  age )
    {
        return "Query Parameters"+" "+"Name:"+name+" "+"Age:"+age;
    }
Note: If no value is pass for name  error will be thrown at runtime.

3. @FormParam :

Form param is used to obtain values of the Form elements.

Ex:

  @Path("/posted")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public String  putJson(@FormParam("name")String name ) {    
        return name;
    }

Here, name is the name of the text field or some other field declared inside the Form tag. 
Note: If no value is pass for name null will be return.

4. @MatrixParam :

The Matrix Param is used to accept values in name & value pair unlike Query Parameter it does not need any questionmark to begin with nor any and (&)sign to specify multiple values. Multiple values can be represented using semicolon(;)

Ex:
 @Path("/MyMethod")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String  putMatrix(@MatrixParam("name")String name,@MatrixParam("age")int age)
    {
       return "Name:"+name+"Age:"+age ;
    }

Note: If no value is pass for name and age null will be return.


Useful Classes:
  •  MediaType 
  •  Response
  • JSONObject & JSONArray

1. MediaType :

This class can be used to represent the MIME Types in the form of Constants.

Ex:

@Produces (MediaType.TEXT_PLAIN)
 Equivalent to 
@Produces ("text/plain")


2. Response:

The Response class one of the widely used , it can be used to return response as text,images,files etc.Instead of being returning as String we should return the Response Object and let Jersey to do the remaining writing to the output stream and other stuffs.

Writing text Response

Ex:

    @Path("/matrix")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response putMatrix(@MatrixParam("name")String name,@MatrixParam("age")int age)
    {
       return Response.ok("Name:"+name+"Age:"+age).build();  
    }
 The Response.ok method takes the String as an Entity and builds it adds to the Output as response.


  Writing Image Response:

   @GET
    @Path("/getData")
    @Produces("image/jpg")
    public Response getData()
    {
        File f=new File("G:\\Icons\\en.jpg");
        Response.ResponseBuilder builder=Response.ok((Object)f);
        builder.header("Content-Disposition","attachment; filename=\"file_from_server.jpg\"");
                return builder.build();
    }
   
 3.JSONObject  & JSONArray :

The JSON Object class is used to create a list of JSON Objects. 

Ex:

        JSONObject jSONObject=new JSONObject();
        jSONObject.put("FirstName", "Jack");
        jSONObject.put("LastName", "Sparrow");
        jSONObject.put("Address", "America");
        System.out.println(jSONObject);

    Output :
    {"FirstName":"Jack","LastName":"Sparrow","Address":"America"}
   
    The JSON Array class is used to create an Array of JSON Objects.

Ex:     

       JSONObject jSONObject=new JSONObject();
        jSONObject.put("FirstName", "Jack");
        jSONObject.put("LastName", "Sparrow");
        jSONObject.put("Address", "America");
        JSONArray array=new JSONArray();
        array.put(jSONObject);
        System.out.println(array);

Output:  [{"FirstName":"Jack","LastName":"Sparrow","Address":"America"}]

Even though Jersey with JAXB, support automatic conversion or implementation of JSON and XML from simple Java Bean with setter/getters, It is good to know how to do it manually.

In the Next Part we will see how to produce XML and JSON output manually, and with Automatic Implementation Provided by Jersey along with JAXB.




Please provide your valuable comments.
Thanks for reading..



<< Prev                                              Index                                Next >>

---------------------------------------------------------------------------------------------------------










Technology Blogs
blogs

12 comments:

  1. a very usefull and easy understandable tutorial
    i love it (javeed mohammed)

    ReplyDelete
  2. useful and easily understandable tutorials on Java Web Services Training

    Java Training in Chennai

    ReplyDelete
  3. Nice information to learn Web Service.
    But there are syntax errors in your given code. I think, it should not be in such an excellent series. You should correct it.

    ReplyDelete
  4. Only certain games ѡill work, and օnly certain Nvidia hardware աill suppot hardware acceleration օf Phhys - X.

    Eveen inn numerous PEOPLE cities lіke Springfield аnd Summit you wiill
    find a lot of residents driving around withіn theіr Ford vehicles.

    Ƴour transport options in Thailaand usuаlly are not expensive bbut aare not speedy аs well.


    Hеre is my blog post :: mirrors edge keygen

    ReplyDelete
  5. What's up, just wantted to mention, I likjed this post. It was funny.

    Keep on posting!

    Here is my blog post - วิธีการสมัคร m88

    ReplyDelete
  6. Howdy! I know this is kinda off topic nevertheless
    I'd figured I'd ask. Would you be interested in trading links or maybe guest writing a blog post
    or vice-versa? My blog discusses a lot of the same subjects as yours and I think we could greatly benefit
    from each other. If you happen to be interested feel free to
    shoot me an email. I look forward to hearing from you!
    Terrific blog by the way!

    My web blog ... chihuhua

    ReplyDelete
  7. Hey There. I found your blog using msn. This is a really well
    written article. I will be sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will definitely comeback.

    My page; price of private jets

    ReplyDelete
  8. of course like your web site however you have to chek the selling on several of your posts.
    Several oof them are rife with spelling problems and I to find it very troublesome to inform the reality then again I will definitely come back again.

    Also viit my webpage; 7m.cn

    ReplyDelete
  9. Interesting article. Thanks for the post.
    Shashaa
    HTML5 Training in Chennai

    ReplyDelete