如何筛选JAX-RS中具有无效参数的请求? [英] How to filter a request that has an invalid parameter in JAX-RS?
本文介绍了如何筛选JAX-RS中具有无效参数的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
@Path(/)
public interface ExampleInterface {
@GET
@Path(/ example)
public Response(
@QueryParam(param1)String param1,
@QueryParam(param2)字符串参数2
);
$ / code>
然后我调用... / example ?param3 = foo
解决方案
您可以使用 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 = resourceInfo.getResourceMethod(); (Annotation [] annos:method.getParameterAnnotations()){
for(Annotation anno:annos){
if(anno instanceof QueryParam){
validParams.add(( (QueryParam)anno).value());
$(b)如果(!validParams.contains(param)){b $ b $($)
for(String param:servletRequest.getParameterMap()。keySet
requestContext.abortWith(Response.status(Status.BAD_REQUEST).build());
不要忘记 ServletRequest#getParameterMap 返回一个包含查询字符串参数和请求主体中传递的参数的Map。所以也许你需要自己解析查询字符串。
注意:这不会加快您的应用程序。
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"
解决方案 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.
这篇关于如何筛选JAX-RS中具有无效参数的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文