Compilation of already published Articles/Ideas/Problems-Solutions which I faced or came across over the period of time. Largely a place for me to document it as note-to-self. Nothing serious. :)

Thursday, November 21, 2013

RESTEasy tutorial part two: web parameters

In the first RESTEasy tutorial we have learnt the basics about REST Web services and we have tested a simple RESTful Web service. In this tutorial we will show how to inject web application elements (form parameters, query parameters and more) into a RESTful Web service.

You can use the following annotations to bind HTTP requests to a RESTful web service:

@FormParam

@PathParam

@QueryParam

@HeaderParam

@CookieParam

@MatrixParam

Let's explore all the possible interactions.

@FormParam

The annotation @FormParam can be used to inject the parameters of a Web form into a RESTful Web service.

Here's an example:

Here we are submitting a POST request containing two parameters email and password which are translated into the parameters "e" and "p" of the login method.

As an alternative, you can bind the parameters email and password at class level, which can be useful if you need to re-use the same parameters across different methods of the service.

1.publicclassUser {

2.

3.@FormParam("email")

4.privateString email;

5.@FormParam("password")

6.privateString password;

7.

8.}

You would need to modify the REST method accordingly:

1.@POST

2.@Path("login")

3.publicString login(@FormUser form) {

4.return"Logged with "+ form.email + " "+ form.password;

5.}

@PathParam

The @PathParam annotation binds the value of a path segment to a resource method parameter. For example, the following method would intercept an HTTP GET like http://server:port/login/12345 and convert the PathParam "12345" into the String "id"

01.@Path("/")

02.publicclassLoginService

03.{

04.

05.@GET

06.@Path("login/{zip}")

07.publicString login(@PathParam("zip") String id) {

08.return"Id is "+id;

09.}

10.}

As for @FormParam, you can embed the @PathParam declaration at class level, if you prefer.

@QueryParam

The @QueryParam annotation binds the value of a path segment to a resource method parameter. For example, the following method would intercept an HTTP GET like http://server:port/login?zip=12345 and inject the query parameter "zip" into the method parameter "zip"

01.@Path("/")

02.publicclassLoginService

03.{

04.

05.@GET

06.@Path("login/{zip}")

07.publicString login(@QueryParam("zip") String zip) {

08.return"Id is "+id;

09.}

10.

11.}

QueryParam can be convenientely used with the DefaultValue annotation so that you can avoid a null pointer exception if no query parameter is passed.