Monday, January 26, 2015

RestWebService

Simple Rest Creation


Steps for rest creation 

If we want to create Rest webService so we have to follow following rules:
  1. Create Project RestWebService and inside src,create  package com.pankaj.rs.
  2. Create class RestDemo.java.
  3. Use annotation @Path and give path like this:@Path("resttest")
  4. Create one method inside that class:restTest().
  5. use annotation again GET. It will accept the request which will come by path.
  6. Use annotation again for display the output as you want. @Produces(MediaType.TEXT_PLAIN). it will return the output in Text Format.

you can see the code given below:

package com.pankaj.rs;

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;

@Path("resttest")
public class RestDemo {
       
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String restTest() {
        return "welcome to rest Service";
    }
       
}

  7. After that deploy this application in Tomme Server/Tomcat Server.
  8. you can access this service in your Browser by given path:
     http://localhost:8080/RestWebService/resttest/


    OUTPOUT: welcome to rest Service


Two request Handle by One Service:

For that you have to give path inside the class on the the top of the method like given below.
If we want to send any value from url the we have to use specific way in path annotation and we have to use @PathParam("userValue") String name in method parameter.It will same as the value we are passing in path variable.
@Path("resttest/{userValue}").

Full Code is given  below:

package com.pankaj.rs;

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;


public class RestDemo {
    //String name ="Hello Rest";
    @Path("resttest")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String restTest() {
        return "welcome to rest Service";
    }
   
    @Path("resttest/{userValue}")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String restTestParam(@PathParam("userValue") String name) {
        return name;
    }
   
}

After that deploy in Tomme Server.

   when you will normal url:
   http://localhost:8080/RestWebService/resttest/
         
      outpout: welcome to rest Service
 
 
   when you will give parameter in URL the output will be different.

http://localhost:8080/RestWebService/resttest/I%20love%20my%20India
     outtput:I love my India

No comments:

Post a Comment