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.
That’s it. Now try adding custom greeting to your local URL as shown below:
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.
- via URL query parameter
- via URL path
- via HTTP Header
- via HTTP POST body
- via cookie
JAX-RS provides various mechanisms to process the data from client requests in your service. Here are few:
- @QueryParam – to read query parameters from URL
- @HeaderParam – to read data from HTTP header
- @FormParam – to read data from HTTP POST form
- @PathParam – to read from the URL path
- @MatrixParam – to read from the URI matrix values
- @CookieParam – to read cookie data sent from the client
- @Context UriInfo – to get all the URI related information via a single object
- @Context HttpHeaders – to read all the header information via a single object
- @BeanParam – to read data from one of the aforementioned ways and bind it to a custom bean.
- MultivaluedMap<String, String> formParams – to read all the form parameters as a map without using annotations