3

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
nullptr
  • 3,320
  • 7
  • 35
  • 68
  • 1
    The "why" part of a question is answered [here](http://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern) – fracz Oct 28 '14 at 07:50
  • 2
    you need to elaborate more about other servlet that you have. Expectation is not clear. – Juned Ahsan Oct 28 '14 at 07:51
  • 1
    Check http://stackoverflow.com/questions/1030302/how-can-i-map-a-root-servlet-so-that-other-scripts-are-still-runnable/9503668#9503668 – Daniel Oct 28 '14 at 07:59
  • Related: [difference between / and /* in Servlet mapping](http://stackoverflow.com/q/4140448). – BalusC May 11 '16 at 10:53

2 Answers2

4

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 ("").

Jakub Kubrynski
  • 13,724
  • 6
  • 60
  • 85
-1

Your servlet url mapping is empty.

<url-mapping>/</url-mapping>

So this url

http://localhost:8084/project/<any_url_given>

doesn't point to any specific servlet class rather it tells you any url pattern it accept e.g http::/.

If your servlet mapping be like

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

and if you enter the url

http://localhost:8084/project/hell

Then com.project.servlets.Hell servlet should be invoked.

Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34