How to handle 404 error in Struts

The “HTTP Status 404” error code is show that the system can not find the page or resource you requested. In practice, you should display your custom 404 error page. However, it is handle in web.xml , not in Struts framework. For example,


<web-app>
  ...
  <error-page>
    <error-code>404</error-code>
    <location>/pages/error404.jsp</location>
  </error-page>
  
</web-app>

When system hit the 404 error, it will forward to your custom 404 error page “/pages/error404.jsp“.

struts-config.xml


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Maven Struts Examples</display-name>
 
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>
 
  <error-page>
    <error-code>404</error-code>
    <location>/pages/error404.jsp</location>
  </error-page>
  
</web-app>

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
7 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
tellmehow.cosoapVenkateshMadHairSilenceSanjeev Kafle Recent comment authors
newest oldest most voted
Sanjeev Kafle
Guest
Sanjeev Kafle

Hi,
This website is great. I have one confusion though. The file shown above looks like WEB.XML but you wrote STRUTS-CONFIG.XML (in bold above).
Thank you.

tellmehow.co
Guest
tellmehow.co

As @Sanjeev, told you wrote struts-config.xml instead of web.xml. Please change that.

soap
Guest
soap

There is Chinese garbled code in your website
—come from Chinese greating

soap
Guest
soap

66666?????

soap
Guest
soap

66666?????

Venkatesh
Guest
Venkatesh

But it is not redirecting to error page when we configure in web.xml.Please refer the below code<

404
/404error.jsp

Charles Morin
Guest
Charles Morin

Thank you, very helpful!

Go
Guest
Go

hi,
This post was more helpful.when I include the error tag in web.xml.I got the error stating “The word ‘jsp’ is not correctly spelled” .What could be the reason?

MadHairSilence
Guest
MadHairSilence

give

/error.jsp

instead of simply

error.jsp