servletsurl-pattern

How to map an "Index Servlet" on root URL pattern of /


I have these two lines in my web.xml

<url-pattern>/</url-pattern> : Index Servlet
and
<url-pattern>/login</url-pattern> : Login Servlet

but whem I open http://localhost:8084/login/, it goes to Index Servlet and when I open http://localhost:8084/login, it goes to Login Servlet.

Is there any difference in http://localhost:8084/login/ and http://localhost:8084/login?

My web.xml

<servlet>
    <servlet-name>Index</servlet-name>
    <servlet-class>Index</servlet-class>
</servlet>
<servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>Login</servlet-class>
</servlet>
and

<servlet-mapping>
    <servlet-name>Index</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

Solution

  • The URL pattern of / has a special meaning. It namely indicates the "Default Servlet" URL pattern. So every request which does not match any of the other more specific URL patterns in web.xml will ultimately end up in this servlet. Note that this thus also covers static files like plain vanilla HTML/CSS/JS and image files! Normally, the "Default Servlet" is already provided by the servlet container itself (see e.g. Tomcat's DefaultServlet documentation). Overriding the "Default Servlet" in your own webapp should be done with extreme care and definitely not this way.

    You need to give your index servlet a different URL pattern. It should be the same as the one you definied in <welcome-file>.

    So in case of

    <welcome-file-list>
        <welcome-file>index</welcome-file>
    </welcome-file-list>
    

    you need to map the index servlet as follows

    <servlet-mapping>
        <servlet-name>Index</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
    

    Using an URL rewrite filter as suggested by other answer is unnecessary for the particular purpose you had in mind.

    See also: