-1

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 "/".

Aakash Verma
  • 3,705
  • 5
  • 29
  • 66
  • Also, "/" and "/*" are behaving in the same manner and when I say "/*", I don't mean "/" followed by "/*" as in a directory match! – Aakash Verma Jun 23 '17 at 06:22
  • This question already have answer here [Difference between / and /* in servlet mapping url pattern](https://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern) – raviraja Jun 23 '17 at 09:52

1 Answers1

1
<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

Fady Saad
  • 1,169
  • 8
  • 13
  • you mean how to type it in web.xml? – Fady Saad Jun 23 '17 at 06:10
  • I am sorry for that wrongly typed comment. I didn't understand "/*", I understood why "/" was behaving as it was from your answer and [here](https://www.coderanch.com/t/366340/java/servlet-mapping-url-pattern). Also, what about empty string? Please include it in your answer. – Aakash Verma Jun 23 '17 at 06:15
  • Done, I update my answer – Fady Saad Jun 23 '17 at 06:19