Using parameter converters in JAX-RS

Injection made easy

JAX-RS provides simple set of API components to make it easy to extract information from your HTTP requests. It takes care of all the heavy lifting – all you need to do is use the applicable annotation (from the list below) and the container will inject the data for you

  • @MatrixParam, @QueryParam, @PathParam: injects URI related info
  • @HeaderParam, @CookieParam: takes care of headers and cookies sent along with a HTTP request
  • @FormParam: handles form data (application/x-www-form-urlencoded content type) POSTed over HTTP

but there are a few rules…

As far as automatic injection is concerned, JAX-RS applies the following constraints

  • applicable for Java primitives (or equivalent wrappers) and String (of course)
  • A custom type which has a static valueOf method or public constructor (both should accept a single parameter of type String)
  • Supported Collections types: List, Set (whose generic type parameters comply with above mentioned rules)

what about exceptional scenarios ?

More often than not, you would need to deal with data types which do not comply with the above rules. Also, you might not have the ability to retrofit (change) the actual source. In such scenarios, you can use a ParamConverter implementation to provide custom conversion logic of your HTTP request data (String) to your desired Java type. Here is an example

we are not done yet !

The ParamConverter implementation is not the actual provider which the JAX-RS runtime accesses directly. A ParamConverterProvider implementation provides another layer of abstraction in order to select the right ParamConverter for the job.

To be noted…

  • The JAX-RS runtime automatically passes some parameters in the getConverter method. This allows for some extra processing/decision making logic based on the parameters passed in by the JAX-RS runtime
  • The ParamConverter and ParamConverterProvider interfaces were introduced in JAX-RS 2.0 (part of Java EE 7 Platform)

Just click here for some of my previous JAX-RS posts


About Abhishek

Currently working as a Senior Product Manager in the Oracle Cloud Application Development team with a focus on Oracle Cloud PaaS portfolio. When not hovering in the clouds, I stay grounded with Java EE
This entry was posted in Java EE and tagged , , . Bookmark the permalink.

3 Responses to Using parameter converters in JAX-RS

  1. Pingback: Java Weekly 4/16: Lazy with Java, Executors, Optimizing Locks

  2. Dennis says:

    Thank You


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s