I am writing a filter to do a specific task but I am unable to set a specific url pattern to my filter. My filter mapping is as follows:
As noted by others, there is no way to filter with regular expression matching using only the basic servlet filter features. The servlet spec is likely written the way it is to allow for efficient matching of urls, and because servlets predate the availability of regular expressions in java (regular expressions arrived in java 1.4).
Regular expressions would likely be less performant (no I haven't benchmarked it), but if you are not strongly constrained by processing time and wish to trade performance for ease of configuration you can do it like this:
In your filter:
private String subPathFilter = ".*";
private Pattern pattern;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String subPathFilter = filterConfig.getInitParameter("subPathFilter");
if (subPathFilter != null) {
this.subPathFilter = subPathFilter;
}
pattern = Pattern.compile(this.subPathFilter);
}
public static String getFullURL(HttpServletRequest request) {
// Implement this if you want to match query parameters, otherwise
// servletRequest.getRequestURI() or servletRequest.getRequestURL
// should be good enough. Also you may want to handle URL decoding here.
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
Matcher m = pattern.matcher(getFullURL((HttpServletRequest) servletRequest));
if (m.matches()) {
// filter stuff here.
}
}
Then in web.xml...
MyFiltersName
com.example.servlet.MyFilter
subPathFilter
/org/test/[^/]+/keys/.*
MyFiltersName
/*
It's also sometimes convenient to make the pattern exclude the match by inverting the if statement in doFilter()
(or add another init param for excludes patterns, which is left as an exercise for the reader.)