java url过滤,特定于请求参数的Java过滤器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&.......

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?

解决方案

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");

}

}

The configuration would look like this in your web.xml:

myFilter

mypackage.MyFilter

pattern

{{PATTERN HERE}}

myFilter

/*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值