特定于请求参数的JavafilterURL模式

我们有一种情况,我们想对包含一些特定请求参数的URL使用filter,例如:

 HTTP://mydomain.com/ ID = 78&formtype = simple_form&.......    
 HTTP://mydomain.com/ ID = 788&formtype = special_form&.......    

依此类推, id是在运行时获取的,我想只在formtype=special_form时才在web.xml配置filter。 应该如何实现解决方案? 可以使用正则表达式模式配置filter吗?

据我所知,没有解决方案直接在web.xml通过查询字符串匹配filter请求。 因此,您可以使用init-params在web.xml注册filter,以使filter可配置,并通过javax.servlet.Filter实现中的void init(FilterConfig filterConfig)设置模式。

 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 mypackage.MyFilter  pattern {{PATTERN HERE}}    myFilter /*  

进一步阅读:
http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html

您必须解析filter正文中的URL参数, 而不是在web.xml中 ;

我做了这样的事情,但我使用了一个阶段监听器,一个配置条目(在配置文件中),它将URL params映射到处理特定“action”的类的FQN(通过action我的意思是来自GET / POST的URL参数) ); 相位监听器将解析来自每个GET / POST的所有URL参数,并将它们中的每一个发送到Dispatcher。 Dispatcher的工作是调用正确的处理程序(对应于该URL参数的FQN的单例对象)。 然后,处理程序只使用他收到的URL值执行特定操作。

使用filter而不是相位监听器可以做同样的事情。