Last active
August 27, 2015 02:44
-
-
Save ar-/c73af00c41bdbb18c08c to your computer and use it in GitHub Desktop.
How to filter a request that has an invalid parameter in JAX-RS? This ContainerRequestFilter returns error 400 (bad request) if there is an unexpected parameter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.lang.annotation.Annotation; | |
import java.lang.reflect.Method; | |
import java.util.HashSet; | |
import java.util.Set; | |
import javax.ws.rs.QueryParam; | |
import javax.ws.rs.container.ContainerRequestContext; | |
import javax.ws.rs.container.ContainerRequestFilter; | |
import javax.ws.rs.container.ResourceInfo; | |
import javax.ws.rs.core.Context; | |
import javax.ws.rs.core.MultivaluedMap; | |
import javax.ws.rs.core.Response; | |
import javax.ws.rs.core.Response.Status; | |
import javax.ws.rs.ext.Provider; | |
@Provider | |
public class UnexpectedParameterFilter implements ContainerRequestFilter { | |
@Context | |
private ResourceInfo resourceInfo; | |
@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()); | |
} | |
} | |
} | |
MultivaluedMap<String, String> queryParameters = requestContext.getUriInfo().getQueryParameters(); | |
for (String param : queryParameters.keySet()) { | |
if (!validParams.contains(param)) { | |
requestContext.abortWith(Response.status(Status.BAD_REQUEST).entity("unexpected paramter: "+param).build()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment