Can we use regular expressions in web.xml URL patterns?

前端 未结 6 2060
我在风中等你
我在风中等你 2020-11-27 05:02

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:



        
6条回答
  •  庸人自扰
    2020-11-27 05:38

    The previous responses are correct in that a url-pattern can only begin or end with a wild-card character, and thus the true power of regex cannot be used.

    However, I've solved this issue on previous projects by creating a simple default filter that intercepts all requests and the filter contains regex to determine whether further logic should be applied. I found that there was little to no performance degradation with this approach.

    Below is a simple example that could be enhanced by moving the regex pattern to a filter attribute.

    Filter configuration within the web.xml:

    
        SampleFilter
        org.test.SampleFilter
    
    
        SampleFilter
        SampleServlet
    
    
        SampleServlet
        /*
    
    

    Basic filter implementation that could use any regex pattern (sorry, uses Spring's OncePerRequestFilter parent class):

    public class SampleFilter extends OncePerRequestFilter {
    
        @Override
        final protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            if (applyLogic(request)) {
                //Execute desired logic;
            }
    
            filterChain.doFilter(request, response);
        }
    
        protected boolean applyLogic(HttpServletRequest request) {
            String path = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
    
            return PatternMatchUtils.simpleMatch(new String[] { "/login" }, path);
        }
    }
    

提交回复
热议问题