Tomcat ROOT webapp: Proper redirection

If you are deploying your web application to a Tomcat server under a specific path then in most cases you want to make sure that the root path and any possible error messages outside of the scope of your application redirect properly to your web app.

You want to do that because of a clean user experience. The user should not see any error messages if he types in the URL of your app and does not enter the correct path at the end. Then there are security aspects because you do not have to leak the fact that you are using Apache Tomcat and the version information which is displayed at the bottom of error messages by default.

Let’s have a look at how to set this up.

Tomcat configuration

For this example I will be using an Apache Tomcat server version 8.5 but the following configuration should be working in any version higher than 7.0. I’m demonstrating this using the Tomcat server running in Eclipse but you can of course work directly with Tomcat and add the web modules to the webapp folder directly.

Besides your web application – which is named mywebapp in this case – you need a webapp called ROOT; the uppercase letters are important. If you add this to a Tomcat without further context configuration it will be deployed under the root path or the slash without any further path elements.

The ROOT webapp

Inside the ROOT webapp you place an index.jsp file that contains the following code:

<%
  final String redirectURL = "/mywebapp/";
  response.setStatus(response.SC_MOVED_PERMANENTLY);
  response.sendRedirect(redirectURL);
%>

This sends a HTTP response with status code 301 to the browser so it knows that this path has been “Moved Permanently” to another location. Adjust the path to your web application as needed.

Adding a web.xml

Put the following web.xml file in a directory WEB-INF of your ROOT webapp:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>Redirect</display-name>

	<servlet>
		<servlet-name>index</servlet-name>
		<jsp-file>/index.jsp</jsp-file>
	</servlet>

	<servlet-mapping>
		<servlet-name>index</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<error-page>
		<location>/index.jsp</location>
	</error-page>
</web-app>

This way a path like /not-there or /is-not-here.jsp or even /foo/bar gets redirected to the error page which is the index.jsp in our case. All these scenarios are correctly handled and redirected to our web application.