dev777 dev777 - 5 months ago 62
Java Question

How to handle optional parameters in CXF restful webservices

I have followed this link for building CXF Restful webservices url link.

If suppose my url is as mentioned below :

http://localhost:8080/CxfRestService/rest/employeeservices/getemployeedetail?employeeId=1&empProfession=software


Here,"empProfession" parameter is optional for me.

So,eventhough if I omit that parameter and hit the below url, I should get the required response.
http://localhost:8080/CxfRestService/rest/employeeservices/getemployeedetail?employeeId=1


Can anyone please help me out how to use optional parameters in the CXF Restful webservices.

Answer

Option 1 - Declare the parameter and check if != null

 public Response getEmployeeDetail(@QueryParam("employeeId") String employeeId, @QueryParam("empProfession") String empProfession);

Option 2 - Declare en object to receive all known parameters

 public Response getEmployeeDetail(@QueryParam("") EmployeeFilter filter) ;

 public class EmployeeFilter {
    public void setEmployeeId(String id) {...}
    public void setEmpProfession(String p) {...}  
 }

Option 3 - Do not declare parameters and parse the URI. This option could be useful if you can accept non-fixed parameters

 public Response getEmployeeDetail( @Context UriInfo uriInfo) {
      MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
      String employeeId = params.getFirst("employeeId");
      String empProfession = params.getFirst("empProfession");
Comments