Servlet mapping for web root


Suppose, you don’t want to put an index.jsp file in the web root and give access to that directly when people go to “http://example.com/”, rather you want to have a HomeController (or whatever) Servlet which will handle the request that comes to the web root. And here comes the problem, there’s no url-pattern for that particular servlet-mapping. @WebServlet(“”) or @WebServlet(“/”) doesn’t work here.

I solved the problem using tuckey url re-writer. I mapped the HomeController to ‘/home’ i.e. @WebServlet(“/home”) and
then re-writing url $^ to /home.
i.e.
File: urlrewrite.xml:

<rule>
	<from>^/$</from>
	<to>/home</to>
</rule>

That worked fine but didn’t satisfy me. One day suddenly a trick came to my mind. I tested it and it worked like a charm! Here’s what I did:

File: web.xml:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>Home</servlet-name>
    <servlet-class>net.hasnath.web.HomeController</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>Home</servlet-name>
     <url-pattern>/index.jsp</url-pattern>
</servlet-mapping>

Basically it works this way: requests to the root i.e. url with no filename specified, comes to index.jsp since index.jsp is in the welcome-file-list. But then there’s a servlet mapping for the url-pattern of ‘/index.jsp’. And so the request is passed to that servlet. pretty simple, right?

Leave a Reply