JAX-RS @DefaultValue Annotation Example with RESTEasy 3
March 13, 2015
In this page, we will learn how to use JAX-RS @DefaultValue annotation with RESTEasy 3. To assign some default values to optional parameter, JAX-RS provides @DefaultValue annotation which can be used with different parameter like @QueryParam and @HeaderParam etc. We define it as below.
public Response getData(@QueryParam("id") @DefaultValue("100") String id){}
Create Service Class
In the example, we have created a method, which is using @DefaultValue annotation.EmployeeService.java
package com.concretepage; import java.util.HashMap; import java.util.Map; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/manage" ) public class EmployeeService { @GET @Path("/data") @Produces("application/json") public Response getEmp(@QueryParam("id") @DefaultValue("100") String id, @QueryParam("company") @DefaultValue("Default-XYZ") String company) { Map<String,String> map = new HashMap<String,String>(); map.put("id", id); map.put("company", company); return Response.ok(map).build(); } }
Output
Find the output with different values.1. URL: http://localhost:8080/resteasyservice-1/employee/manage/data
Both the parameter has not been given input values, so we will get default values.
{"company":"Default-XYZ","id":"100"}
2. URL: http://localhost:8080/resteasyservice-1/employee/manage/data?id=200
First parameter has been given input and second parameter is left, so it will be assigned with default values.
{"company":"Default-XYZ","id":"200"}