java 所有请求的 Servlet 过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7949908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Servlet Filter for all requests
提问by fernandohur
I am wondering, how can I set in the web.xml a Filter that is called on every request?
我想知道,如何在 web.xml 中设置一个对每个请求调用的过滤器?
回答by aishwarya
just create a filter, and map it to /*
只需创建一个过滤器,并将其映射到 /*
e.g.
例如
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.mycompany.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
回答by Saurabh Saxena
Add a filter mapping with '*' wildcard.
添加带有“*”通配符的过滤器映射。
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
回答by Paramvir Singh Karwal
Spring Security Webdefines all urls as /**
. So it should work for all requests.
Spring Security Web将所有 url 定义为/**
. 所以它应该适用于所有请求。
See-
org.springframework.security.web.util.matcher.AntPathRequestMatcher
看-
org.springframework.security.web.util.matcher.AntPathRequestMatcher
It defines MATCH_ALL
constant as /**
and this final variable is used in matches
method.
它将MATCH_ALL
常量定义为,/**
并且在matches
方法中使用了这个最终变量。
Pasting below the method definition from org.springframework.security.web.util.matcher.AntPathRequestMatcher
where it decides if some request url matches or not. If the pattern is set to MATCH_ALL
aka /**
it returns true
.
粘贴在方法定义下方,从org.springframework.security.web.util.matcher.AntPathRequestMatcher
那里决定某个请求 url 是否匹配。如果模式设置为MATCH_ALL
aka/**
它返回true
。
public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && StringUtils.hasText(request.getMethod())
&& this.httpMethod != valueOf(request.getMethod())) {
if (logger.isDebugEnabled()) {
logger.debug("Request '" + request.getMethod() + " "
+ getRequestPath(request) + "'" + " doesn't match '"
+ this.httpMethod + " " + this.pattern + "'");
}
return false;
}
if (this.pattern.equals(MATCH_ALL)) {
if (logger.isDebugEnabled()) {
logger.debug("Request '" + getRequestPath(request)
+ "' matched by universal pattern '/**'");
}
return true;
}
String url = getRequestPath(request);
if (logger.isDebugEnabled()) {
logger.debug("Checking match of request : '" + url + "'; against '"
+ this.pattern + "'");
}
return this.matcher.matches(url);
}
回答by Philip Rego
Are you sure the request is hitting the controller/servlet? If it's making an Ajax call or running some JS then the filter won't hit.
您确定请求正在击中控制器/servlet?如果它正在执行 Ajax 调用或运行一些 JS,那么过滤器将不会命中。