servletscase-sensitiveurl-pattern

Servlet URL pattern case sensitivity


I have the following code

@WebFilter(urlPatterns = "/path/to/directory/*")
public class PageFilter extends MyBaseFilter {

}

It works as expected if I do "http://localhost/path/to/directory", but if I do http://localhost/PATH/to/directory" or any other combination the filter does not work. It appears to be case sensitive. Is there a way to make this case insensitive so it matches any permutation of the url?


Solution

  • Is there a way to make this case insensitive so it matches any permutation of the url?

    No.

    But you can add another filter which sends a 301 (Permanent) redirect to a lowercased URI when the URI contains an uppercased character.

    E.g.

    @WebFilter("/*")
    public class LowerCasedUriFilter extends HttpFilter {
    
        @Override
        public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
            var uri = request.getRequestURI();
            var lowerCasedUri = uri.toLowerCase();
    
            if (uri.equals(lowerCasedUri)) {
                chain.doFilter(request, response);
            }
            else {
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                response.setHeader("Location", lowerCasedUri);
            }
        }
    }
    

    Make sure this filter is registered before yours.