问题
We are using RESTful Web Services (Jersey) for API calls on java. While API needs optional parameter, we are doing as:
api-interface/user/userid/9000/companyid/90909/{optionalparameter*}
and we have to call this api when there is no optional parameter as:
api-interface/user/userid/9000/companyid/90909/
What needed is:
Case:1 If optional parameter exists
api-interface/user/userid/9000/companyid/90909/name/john/address/MA/age/34
Case:2 If Optional parameter doesn't exists.
api-interface/user/userid/9000/companyid/90909
My present implementation is:
@GET
@Path("user/companyid/{companyid}/userid/{userid}/{optionalparameter:.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserList(@PathParam("companyid") String companyId, @PathParam("userid") String userId,
@PathParam("optionalparameter") String syncDate) throws BadRequestException, InternalServerException {
//parsing the param.
}
In above code, I need to add trailing "/" but I am looking the way to remove this trailing "/" if anybody doesn't wants to pass those param.
I followed this link but it didn't worked while the preceding parameter's length is more then 1.
Please, Suggest me the best way.
回答1:
Looking at your reference, have you tried this:
@Path("userid/{userid}/companyid/{companyid}{optparam:(/[^/]+?)*}")
public Response getLocation(
@PathParam("userid") int userid,
@PathParam("companyid") int companyid,
@PathParam("optparam") String optparam) {
String[] params = parseParams(optparam);
...
}
private String[] parseParams(String params) {
if (params.startsWith("/")) {
params = path.substring(1);
}
return params.split("/");
}
That should work, giving you all the parameters in a single array.
EDIT: I have updated the search string and verified it on a local install.
来源:https://stackoverflow.com/questions/26377710/remove-from-api-call-when-optional-parameter-is-null