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.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Rajnish KatiyarJean PierreRishabh BhardwajSpring MVC Tutorials Recent comment authors
newest oldest most voted
trackback
Spring MVC Tutorials

[…] 404 error code is not working in Spring MVC […]

Rajnish Katiyar
Guest
Rajnish Katiyar

Worked (y) !

Jean Pierre
Guest
Jean Pierre

Tks, it’s work for me.

Rishabh Bhardwaj
Guest
Rishabh Bhardwaj

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 :