JAX-RS and unknown query parameters

时光总嘲笑我的痴心妄想 提交于 2019-12-05 06:43:31

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 obtain all query parameters by calling getQueryParameters() method. So you know if there are any unknown parameters and you can return error.

but what happens if the client passes in a query parameter that is not implemented

If you implement no special support of handling "unknown" parameters, the resource will be called and the parameter will be silently ignored.

Personally I think that it's better to ignore the unknown parameters. If you just ignore them, it may help to make the API backward compatible.

You should definitely check out the JAX-RS filters (org.apache.cxf.jaxrs.ext.RequestHandler) to intercept, validate, manipulate request, e.g. for security or validatng query parameters.

If you declared all your parameters using annotations you can parse the web.xml file for the resource class names (see possible regex below) and use the full qualified class names to access the declared annotations for methods (like javax.ws.rs.GET) and method parameters (like javax.ws.rs.QueryParam) to scan all available web service resources - this way you don't have to manually add all resource classes to your filter. Store this information in static variables so you just have to parse this stuff the first time you hit your filter.

In your filter you can access the org.apache.cxf.message.Message for the incoming request. The query string is easy to access - if you also want to validate form parameters and multipart names, you have to reas the message content and write it back to the message (this gets a bit nasty since you have to deal with multipart boundaries etc).

To 'index' the resources I just take the HTTP method and append the path (which is then used as key to access the declared parameters.

You can use the ServletContext to read the web.xml file. For extracting the resource classes this regex might be helpful

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!