Search code examples
servletsservlet-filtersservlet-mapping

Any way of mapping java servlet using simple regex?


I need to map /Test to a servlet Test.java and also /anything/Test to the same servlet. I read that /*/Test won't work in web.xml as it doesn't accept regex.

Is there any alternate way of doing it using filters ? I can't use Tuckey URL filter due to some blockage issue. Also, I need that "anything" also in my servlet. I planned to process the url string for that if I am able to map.

For example

/ProjectName/Test Should open Test servlet

and also /ProjectName/xyz/Test Should also open Test servlet

Now xyz can be anything. And I also want to get xyz in my Test servlet. I planned to get xyz in by request.getRequestURI() and fetching it from the url.


Solution

  • You would need a filter.

    This one is a basic one that should work.

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
    
        HttpServletRequest req = (HttpServletRequest) request;
    
        String url = req.getRequestURI();
        if (url.endsWith("test")) {
            request.getServletContext().getNamedDispatcher("TestServlet").forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }
    

    Key points. I use getNamedDispatcher to get the named servlet you wish to use. It's probably best to not actually map this servlet to a pattern at all.

    By using the getNamedDispatcher, it does not corrupt the request url within the destination servlet proper.