我们有一种情况,我们想对包含一些特定请求参数的 URL 使用过滤器,例如:
http://mydomain.com/?id=78&formtype=simple_form&....... http://mydomain.com/?id=788&formtype=special_form&.......
等等,id
是在运行时获取的,我只想在 formtype=special_form
时在 web.xml
中配置过滤器。应该如何实现解决? Filter 可以配置正则表达式模式吗?
最佳答案
据我所知,在 web.xml
中没有直接通过查询字符串将请求匹配到过滤器的解决方案。因此,您可以使用 init-params 在 web.xml
中注册过滤器,使过滤器可配置,并通过 中的
实现。void init(FilterConfig filterConfig)
设置模式javax.servlet.Filter
package mypackage;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
private String pattern;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// check whether we have a httpServletRequest and a pattern
if (this.pattern != null && request instanceof HttpServletRequest) {
// resolve the query string from the httpServletRequest
String queryString = ((HttpServletRequest) request).getQueryString();
// check whether a query string exists and matches the given pattern
if (queryString != null && queryString.matches(pattern)) {
// TODO do someting special
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.pattern = filterConfig.getInitParameter("pattern");
}
}
配置在您的 web.xml 中看起来像这样:
<!-- MyFilter -->
<filter>
<filter-name>myFilter</filter-name>
<filter-class>mypackage.MyFilter</filter-class>
<init-param>
<param-name>pattern</param-name>
<param-value>{{PATTERN HERE}}</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
延伸阅读:
http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html
关于特定于请求参数的 Java 过滤器 URL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521740/