DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Generics in Java and Their Implementation
  • Build a Java Microservice With AuraDB Free
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Trending

  • How to Practice TDD With Kotlin
  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  1. DZone
  2. Data Engineering
  3. Data
  4. Using Parameter Converters in JAX-RS

Using Parameter Converters in JAX-RS

Here's how to use parameter converters in JAX-RS, with injection made simple, rules, and exceptional scenarios.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
Jan. 29, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
24.1K Views

Join the DZone community and get the full member experience.

Join For Free

Injection Made Easy

JAX-RS provides a 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 an 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)
@Path("test")
public class JAXRSInjectionTestResource{
  @HeaderParam("token")
  //Assume that Token has a public ctor with a String param
  private Token token;

  @GET
  @Path("{id}")
  @Produces("application/json")
  public CustDetails fetch(@PathParam("id") String custID){
    //this method will be invoked by a HTTP GET on http://host:port/context-root/test/42
  }
}

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:

public class MyParamConverter implements ParamConverter<MyObject>{

  @Override
  public MyObject fromString(String s){
    //imagine MyObject is a third party class
    return MyObjectFactory.get(s);
  }

  @Override
  public String toString(MyObject mo){
    return mo.toString();
  }
}

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.

@Provider
public class MyParamConverterProvider implements ParamConverterProvider{

    @Override
    public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
        if(rawType.equals(MyObject.class)){
            return (ParamConverter<T>) new MyParamConverter();
        }
        return null;
    }
}

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 …

Data (computing) Java EE Requests Implementation Java (programming language) Strings Data Types Injection career

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Generics in Java and Their Implementation
  • Build a Java Microservice With AuraDB Free
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: