JAX-RS @DefaultValue Annotation Example with RESTEasy 3

By Arvind Rai, 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){} 
If we don't pass the values for id parameter, we will get default value defined as 100.

Create Service Class

In the example, we have created a method, which is using @DefaultValue annotation.
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 {
    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();


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.

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.

Download Complete Source Code


©2023 concretepage.com | Privacy Policy | Contact Us