visual-kinetic visual-kinetic - 7 months ago 21
Java Question

How can a JAX-RS web service only accept form parameters that are sent in the request body?

Let's say I have the following JAX-RS web service:

public class HelloService {

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String getMessage(@FormParam("name") String name) {
return "Hello, " + name + "!";
}
}


This web service will accept form parameters whether they're sent in the request body or sent in the URL (e.g.
http://foo.bar/baz?name=qux
).

Is there a way that I can configure the web service to only accept form parameters that are sent in the request body?

Answer

You could try a ContainerRequestFilter, as following:

@Provider
public class QueryParametersFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        String query = requestContext.getUriInfo().getRequestUri().getQuery();

        if (query != null && !query.isEmpty()) {
            requestContext.abortWith(
                Response.status(Status.BAD_REQUEST)
                        .entity("Parameters not allowed in the query string")
                        .build());
        }
    }
}

The implementation can be taylored to meet your needs.

Important: The above defined filter is global, that is, will be executed for all resource methods. To bind this filter to a set of methods, check this answer.


For dynamic binding, you also could try a DynamicFeature.