I was naive enough to think that the reasonable URL pattern “/” would match only the root path of the application. Guess what, it doesn’t.
Instead it overrides your default servlet and effectively matches ALL your requests that isn’t matched by a servlet with the hilarious result of JS, CSS files and images responding with the same output as your intended front page servlet. Mindboggling.
If you’re lucky enough to use Servlets 3.0 you can specify an empty string “” to match only the root path (http://host:port/<context-path>).
In the web.xml it would be:
<servlet-mapping> <name>Servlet1</name> <url-pattern></url-pattern> </servlet-mapping>
And in annotations it would unsurprisingly be:
@WebServlet(name = "Servlet1", urlPatterns = "")
Well not quite, if you’re using a Tomcat server you’ll still be faced with an java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping exception when building the project if you’re on version less than 7.0.28 (that’s when they patched it).
So what do you do if you’re one of the unlucky ones? Try welcome files.
It could look something like this:
<servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/home</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/home</welcome-file> </welcome-file-list>
AFAIK welcome paths will match in all directories and subdirectories so beware of that.