JAX-RS @QueryParam and @DefaultValue annotations example
This page gives you an example using JAX-RS @QueryParam and @DefaultValue annotations, which injects value from request parameters
to your method input parameters.
In the previous examples we have given details of application setup, dependencies, web.xml file configurations: If you want to
know about these configuration, please refer these:
Restful web services using RESTEasy hello world example.
Restful web services using Jersey hello world example.
Look at the below class to apply @QueryParam annotation: You have two query parameters here: dept and branch.
package com.java2novice.restful;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("/employee")
public class QueryParamExampleService {
@GET
@Path("/query")
public Response getEmployeeQuery(@QueryParam("dept") String department,
@QueryParam("branch") String branch){
String resp = "Query parameters are received. 'dept' value is: "
+department+" and branch value is: "+branch;
return Response.status(200).entity(resp).build();
}
}
|
In the above example, if you use "/employee/query?branch=hydrabad&dept=finance" URI pattern with query parameters, getEmployeeQuery() method will be invoked, and you will get
"Query parameters are received. 'dept' value is: finance and branch value is: hydrabad"
as a response.
How to assign default values to method input variables if the query parameters are not available? You can use @DefaultValue
annotation to specify default value.
package com.java2novice.restful;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("/employee")
public class QueryParamExampleService {
@GET
@Path("/query")
public Response getEmployeeQueryDefault(
@DefaultValue("accounts") @QueryParam("dept") String department,
@DefaultValue("bangalore") @QueryParam("branch") String branch){
String resp = "Query parameters are received. 'dept' value is: "
+department+" and branch value is: "+branch;
return Response.status(200).entity(resp).build();
}
}
|
In the above example, if you use "/employee/query" URI pattern, and you will get "Query parameters are received. 'dept' value is: accounts and branch value is: bangalore"
as a response.
In the next page you will see an example on how to use @MatrixParam annotation.
|