Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a request that has an invalid parameter in JAX-RS?

By "invalid" I mean a parameter that is not expected.

For example:

@Path("/")
public interface ExampleInterface {
    @GET
    @Path("/example")
    public Response test(
        @QueryParam("param1") String param1,
        @QueryParam("param2") String param2
    );
}

And then I call ".../example?param3=foo"

like image 914
Pedro Barros Avatar asked Dec 09 '22 07:12

Pedro Barros


1 Answers

You can check use a ContainerRequestFilter and compare the passed parameters with the defined parameters:

@Provider
public class RequestParamFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Context
    private HttpServletRequest servletRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        Set<String> validParams = new HashSet<String>();
        Method method = resourceInfo.getResourceMethod();
        for (Annotation[] annos : method.getParameterAnnotations()) {
            for (Annotation anno : annos) {
                if (anno instanceof QueryParam) {
                    validParams.add(((QueryParam) anno).value());
                }
            }
        }
        for (String param : servletRequest.getParameterMap().keySet()) {
            if (!validParams.contains(param)) {
                requestContext.abortWith(Response.status(Status.BAD_REQUEST).build());
            }
        }
    }

}

Don't forget that ServletRequest#getParameterMap returns a Map which contains both - query string parameters and parameters passed in the body of the request. So maybe you need to parse the query string yourself.

Note: This won't speed up your application.

like image 93
lefloh Avatar answered Dec 11 '22 10:12

lefloh