How to write a simple RESTful web service using Jersey (Part 3)?

In the previous 2 parts, we saw how to read something via RESTful web service. Here we are going to see how to pass in data from client to the web service? In our “Hello, World” example, what if I want to display a custom greeting instead of a “Hello”?

Create the method that takes in user input parameter.

@GET
@Produces({MediaType.TEXT_PLAIN})
@Path("/plain")
public String getPlain(@DefaultValue("Hello") @QueryParam("greeting") String greeting) {
	return greeting + " World!!!";
}

That’s it. Now try adding custom greeting to your local URL as shown below:
http://localhost:8080/PlayArea-1.0/helloworldapp/helloworldresources/plain?greeting=Welcome

As you can see, the custom parameter “greeting” is passed in via the URL as “?greeting=Welcome” (Multiple parameters can be passed in separated by &). On the server side, the method which processes this request takes in a method parameter annotated with @QueryParam(“greeting”). JAX-RS binds the query parameter value from URL to this method parameter variable. A default value can be assigned to this parameter via @DefaultValue annotation.

Using HTTP, there are several ways to pass data from client to the service. When to use what is a separate topic for another day. For now, let us stick the example above which uses technique #1.

  1. via URL query parameter
  2. via URL path
  3. via HTTP Header
  4. via HTTP POST body
  5. via cookie

JAX-RS provides various mechanisms to process the data from client requests in your service. Here are few:

  1. @QueryParam – to read query parameters from URL
  2. @HeaderParam – to read data from HTTP header
  3. @FormParam – to read data from HTTP POST form
  4. @PathParam – to read from the URL path
  5. @MatrixParam – to read from the URI matrix values
  6. @CookieParam – to read cookie data sent from the client
  7. @Context UriInfo – to get all the URI related information via a single object
  8. @Context HttpHeaders – to read all the header information via a single object
  9. @BeanParam – to read data from one of the aforementioned ways and bind it to a custom bean.
  10. MultivaluedMap<String, String> formParams – to read all the form parameters as a map without using annotations