JAX-RS parameters and unknown query parameters

I have a Java client that calls a RESTEasy (JAX-RS) Java server. Perhaps some of my users may have a newer version of the client than the server.

This client can invoke a resource on the server containing query parameters that the server is not aware of. Is it possible to detect this on the server side and return an error?

I understand that if a client calls a URL that has not yet been implemented on the server, the client will receive a 404 error, but what happens if the client passes a request parameter that is not implemented (for example ?sort_by=last_name )?

+4
source share
2 answers

Is it possible to detect this on the server side and return an error?

Yes you can do it. I think the easiest way is to use @Context UriInfo . You can get all query parameters by calling getQueryParameters() . That way, you know if there are any unknown parameters, and you can return an error.

but what happens if the client goes into a request parameter that is not implemented.

If you do not implement special support for processing "unknown" parameters, the resource will be called and the parameter will be ignored.

Personally, I think it's better to ignore unknown parameters. If you simply ignore them, this can help make the API backward compatible.

+4
source

You should definitely check the JAX-RS filters (org.apache.cxf.jaxrs.ext.RequestHandler) to intercept, verify, process the request, for example. for security parameters or parameter validation.

If you declared all of your parameters using annotations, you can parse the web.xml file for resource class names (see a possible regular expression below) and use the full class names to access the declared annotations for methods (e.g. javax.ws. Rs. GET) and method parameters (for example, javax.ws.rs.QueryParam) for scanning all available web service resources - this way you do not need to manually add all resource classes to your filter. Store this information in static variables, so you just need to parse this material the first time you click on your filter.

In your filter, you can access org.apache.cxf.message.Message for an incoming request. The query string is easy to access - if you also want to check the form parameters and multi-line names, you should use the contents of the message and write it back to the message (this is a bit unpleasant since you have to deal with multi-page borders, etc.).

To β€œindex” resources, I just take the HTTP method and add a path (which is then used as a key to access the declared parameters.

You can use ServletContext to read the web.xml file. For retrieving resource classes, this regular expression may be useful

 String webxml = readInputStreamAsString(context.getResourceAsStream("WEB-INF/web.xml")); Pattern serviceClassesPattern = Pattern.compile("<param-name>jaxrs.serviceClasses</param-name>.*?<param-value>(.*?)</param-value>", Pattern.DOTALL | Pattern.MULTILINE); 
0
source

All Articles