特定于请求参数的Java过滤器URL模式 [英] Java Filter URL pattern specific to request params
问题描述
我们有一种情况,我们想对包含一些特定请求参数的URL使用过滤器,例如:
We have a situation where we want to use filter for URL's containing some specific request parameters, e.g:
http://mydomain.com/?id=78&formtype=simple_form&.......
http://mydomain.com/?id=788&formtype=special_form&.......
依此类推, id
是在运行时获取的,我想在 web中配置过滤器。 xml
仅当 formtype = special_form
时。应该如何实现解决方案?可以使用正则表达式模式配置过滤器吗?
and so on, id
are fetched at run time, I want configure filter in web.xml
only if formtype=special_form
. How should achieve the solution? Can Filter be configured with regex patterns?
推荐答案
据我所知,没有解决方案可以通过查询字符串将请求与过滤器匹配直接在 web.xml
中。因此,您可以使用init-params在 web.xml
中注册过滤器,以使过滤器可配置并通过 void init(FilterConfig filterConfig)设置模式 javax.servlet.Filter
实施中的。
As far as I know there is no solution for matching requests to filters by query string directly in web.xml
. So you could register the filter in your web.xml
using init-params to make the filter configurable and set a pattern via void init(FilterConfig filterConfig)
in your javax.servlet.Filter
implementation.
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:
The configuration would look like this in your 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模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!