简体   繁体   中英

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.

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");

In fact, all parameters in CXF are not mandatory and you cannot change this using @QueryParam (as you can do compared eg with Spring-REST using @RequestParam(required=false)).

The solution is to add the @NotNull javax.validation annotation to indicate that a parameter is mandatory.

This way, you can use

  • CXF3 ValidationFeature to validate it automatically using @Valid.
  • CXF3 SwaggerFeature will also render mandatory parameters in the API documentation
  • CXF2 perform bean validation manually

See the CXF3 ValidationFeature for more info on using the javax.validation annotations: https://cwiki.apache.org/confluence/display/CXF20DOC/ValidationFeature

More about the CXF3 Swagger Feature here: http://cxf.apache.org/docs/swagger2feature.html ).

This answer is related: Required @QueryParam in JAX-RS (and what to do in their absence)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM