特定于请求参数的Java过滤器URL模式

我们遇到一种情况,我们想对包含某些特定请求参数的URL使用过滤器,例如:

http://mydomain.com/?id = 78&formtype = simple_form&......。    

http://mydomain.com/?id = 788&formtype = special_form&......。

等等,id都是在运行时牵强,我想配置过滤器,web.xml只有当formtype=special_form。应该如何解决?可以使用正则表达式模式配置Filter吗?

回答:

据我所知,尚无解决方案可直接在中通过查询字符串将请求匹配到过滤器web.xml。因此,您可以在web.xml使用init-

params的情况下注册过滤器,以使过滤器可配置,并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模式 的全部内容, 来源链接: utcz.com/qa/401084.html

回到顶部