Search code examples
jspservletsdocument-rooturl-pattern

Servlet path "/" returns that servlet content for any request pattern


When I map servlet with path as like:

<servlet>
    <servlet-name>Home1Servlet</servlet-name>
    <servlet-class>com.project.servlets.Home1Servlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Home1Servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

And then when I request servlet from browser by any paths like:

http://localhost:8084/project/
http://localhost:8084/project/asd
http://localhost:8084/project/why
http://localhost:8084/project/hell

All these requests return same Home1Servlet content. Why?

How can map servlet only to path "/"?

I am using Apache Tomcat 6.0.26, Java EE 5. Context path is: /project


Solution

  • If you want to map servlet ONLY to root url then use empty mapping:

    <url-pattern></url-pattern>
    

    It's described in Servlet specification 12.2:

    The empty string ("") is a special URL pattern that exactly maps to the application's context root, that is, requests of the form host:port/<context_root>/. In this case the path info is / and the servlet path and context path is empty string ("").