Annotations for Field and Bean Properties of Resource Classes

JAX-RS annotations for resource classes let you extract specific parts or values from a Uniform Resource Identifier (URI) or request header.
Annotation
Description
@Context
Injects information into a class field, bean property, or method parameter
@CookieParam
Extracts information from cookies declared in the cookie request header
@FormParam
Extracts information from a request representation whose content type is application/x-www-form-urlencoded
@HeaderParam
Extracts the value of a header
@MatrixParam
Extracts the value of a URI matrix parameter
@PathParam
Extracts the value of a URI template parameter
@QueryParam
Extracts the value of a URI query parameter


Extracting Path Parameters

URI path templates are URIs with variables embedded within the URI syntax. The @PathParam annotation lets you use variable URI path fragments when you call a method.

The following code snippet shows how to extract the last name of an employee when the employee’s email address is provided:

@Path(/employees/"{firstname}.{lastname}@{domain}.com")
public class EmpResource {

    @GET
    @Produces("text/xml")
    public String getEmployeelastname(@PathParam("lastname") String lastName) {
     ...
    }
}

In this example, the @Path annotation defines the URI variables (or path parameters) {firstname} , {lastname}, and {domain}. The @PathParam in the method parameter of the request method extracts the last name from the email address.

If your HTTP request is GET /employees/dinesh.rajput@example.com, the value “rajput” is injected into {lastname}.

You can specify several path parameters in one URI.

You can declare a regular expression with a URI variable. For example, if it is required that the last name must consist only of lower and upper case characters, you can declare the following regular expression:

@Path(/employees/{"firstname}.{lastname[a-zA-Z]*}@{domain}.com")

If the last name does not match the regular expression, a 404 response is returned.

Extracting Query Parameters

Use the @QueryParam annotation to extract query parameters from the query component of the request URI.

For instance, to query all employees who have joined within a specific range of years, use a method signature like the following:

@Path(/employees/")
@GET
public Response getEmployees(
        @DefaultValue("2002") @QueryParam("minyear") int minyear,
        @DefaultValue("2010") @QueryParam("maxyear") int maxyear)
    {...}

This code snippet defines two query parameters, minyear and maxyear. The following HTTP request would query for all employees who have joined between 1999 and 2009:

GET /employees?maxyear=2009&minyear=1999
The @DefaultValue annotation defines a default value, which is to be used if no values are provided for the query parameters. By default, JAX-RS assigns a null value for Object values and zero for primitive data types. You can use the @DefaultValue annotation to eliminate null or zero values and define your own default values for a parameter.

Extracting Form Data
Use the @FormParam annotation to extract form parameters from HTML forms. For example, the following form accepts the name, address, and manager’s name of an employee:

<form action="http://example.com/employees/" method="post">

<fieldset>
Employee name: <input name="empname" tabindex="1" type="text" />  
Employee address: <input name="empaddress" tabindex="2" type="text" /> 
Manager name: <input name="managername" tabindex="3" type="text" /> </fieldset>
</form>

Use the following code snippet to extract the manager name from this HTML form:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("managername") String managername) {
    // Store the value
    ...
}

To obtain a map of form parameter names to values, use a code snippet like the following:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String. String> formParams) {
    // Store the message
}

Extracting the Java Type of a Request or Response
The javax.ws.rs.core.Context annotation retrieves the Java types related to a request or response.

The javax.ws.rs.core.UriInfo interface provides information about the components of a request URI. The following code snippet shows how to obtain a map of query and path parameter names to values:

@GET
public String getParams(@Context UriInfo ui) {
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
    MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}

The javax.ws.rs.core.HttpHeaders interface provides information about request headers and cookies. The following code snippet shows how to obtain a map of header and cookie parameter names to values:

@GET
public String getHeaders(@Context HttpHeaders hh) {
    MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
    MultivaluedMap<String, Cookie> pathParams = hh.getCookies();
}

References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago