404 error code is not working in Spring MVC

Problem

In Spring MVC application, the 404 error code is configured properly. See the following web.xml snippet.

File : web.xml


<web-app ...>

  <servlet>
  	<servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
 	<servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

  //...
  <error-page>
	<error-code>404</error-code>
	<location>/WEB-INF/pages/404.htm</location>
  </error-page>

</web-app>

However, when user access any non-exist resources, it will display a blank page instead of the 404.htm.

Solution

The 404 error code is configured properly, but it will caused the “.htm” extension handling conflict between the “servlet container” and Spring’s “DispatcherServlet“. To solve it, try change the 404.htm to other file extension, for example 404.jsp.

File : web.xml


<web-app ...>

  <servlet>
  	<servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
 	<servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

  //...
  <error-page>
	<error-code>404</error-code>
	<location>/WEB-INF/pages/404.jsp</location>
  </error-page>

</web-app>

Now, when user access any non-exist resources, it will forward to the 404.jsp page now.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jean Pierre
11 years ago

Tks, it’s work for me.

Rishabh Bhardwaj
12 years ago

it still doesnt work in my case when i change it to .jsp. I am trying to redirect it to my index page. index.jsp. not working :

Rajnish Katiyar
10 years ago

Worked (y) !