Search code examples
javaservletsurl-pattern

url-pattern "/" vs "/*" vs blank in servlet


When I have "/" as my url-pattern, I can type into whatever I want after the slash in the address bar and land successfully onto the servlet. That is, both

http://localhost:8080/firstServlet/

as well as

http://localhost:8080/firstServlet/any_random_string

gives me the same result.

But when I have url-pattern blank then only http://localhost:8080/firstServlet/ works and everything. Please explain why. There is something here and here similar but I don't understand it exactly.

The pattern "/*" is also behaving just like "/".


Solution

  • <url-pattern>/*</url-pattern>
    

    The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only

    <url-pattern>/</url-pattern>
    

    The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings

    And for empty url pattern

    <url-pattern></url-pattern>
    

    The empty string ("") is a special URL pattern that exactly maps to the application's context root