We're going to look at three examples of passing parameters in JAX-RS Jersey on both the client and the server. We're going to look at:
- Objects sent as Request Headers
- Multiple Objects sent as a Header Hashmap, and
- Objects sent as JSON Entities.
We're looking at tests found in this GitHub Gist, where we're using Bootique Jersey to lay the groundwork in this @BeforeClass initialization code.
Now that we have our Jetty Test Server up and running we'll look at our Parameter Passing Examples.
Passing an Object as a Header Parameter
In our client we set the Web Target as usual, then we convert our Post object to JSON and add it as a header to our request.
On the server we use the @HeaderParam annotation to extract our Post JSON String and convert it back to an Object.
Multiple Objects in a Header
To pass multiple objects in a Request Header we'll do the same JSON conversion of our Post objects as before, but this time place them in a MultiValuedMap<String, Object> for transport.
On the Server we use httpRequest.getHeader() to retrieve each JSON String before performing the final conversion to Post objects.
Passing an Object as a JSON Entity
You'll see that passing an Object in Jersey as a JSON Entity is not unlike passing any ordinary parameter to a method. The only difference being that we're dealing in JSON so we first wrap the Post object in Entity.json().
On the Server there is literally nothing we need to do in the way of conversion, since Jersey handles that for us. Sweet!
Other examples of passing parameters are found in this GitHub Gist.