如何在JAX-RS中过滤具有无效参数的请求?

Ped*_*ros 3 java jax-rs filter query-parameters resteasy

"无效"是指不期望的参数.

例如:

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

然后我打电话 ".../example?param3=foo"

lef*_*loh 10

您可以检查使用ContainerRequestFilter并将传递的参数与定义的参数进行比较:

@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());
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

不要忘记ServletRequest#getParameterMap返回一个Map,它包含 - 查询字符串参数和在请求正文中传递的参数.所以也许你需要自己解析查询字符串.

注意:这不会加快您的申请.