Servlet @WebServlet urlPatterns

kakacii picture kakacii · May 16, 2013 · Viewed 29.1k times · Source

This is a quick question but I couldn't find a quick answer. Now I have a servlet BaseServlet, when user request any of the url below:

host
host/
host/BaseServlet

It should always refer to the same servlet and redirect to the homepage.

When I set

@WebServlet({"/BaseServlet", ""})

Only

host/
host/BaseServlet

works

If I set

@WebServlet({"/BaseServlet", "", "/"})

The BaseServlet will be requested constantly in loop ...

Why?

Edit: BaseServlet does a forward to the index.html hid in WEB-INF folder and that's it.

getServletContext().getRequestDispatcher("/WEB-INF/index.html").forward(request,response);

The servlet spec says "A string containing only the / character indicates the "default" servlet of the application." So I want the BaseServlet to be my default. Why it doesn't work?

Answer

Glen Best picture Glen Best · Jun 28, 2013
  1. As you state in your Q, if you want the following:

    host/
    host/BaseServlet
    

    Use

    @WebServlet({"/BaseServlet", ""})
    
  2. If you want the following:

    host
    

    Add this to your welcome file (you can't specifiy welcome files using annotations)

    <welcome-file-list>
        <welcome-file>/BaseServlet</welcome-file>
    </welcome-file-list>
    
  3. The servlet spec says "A string containing only the '/' character indicates the "default" servlet of the application."

    But it says straight afterwards

    In this case the servlet path is the request URI minus the context path and the path info is null.

    In other words, if your URL is

    host
    

    then the servlet path will be

    "" (empty string)
    

    so you will need a welcome file list (but index.htm[l] and index.jsp in the webapp directory, not WEB-INF, are included implicitly as a starting welcome file list)