Reputation: 23800
How can I make sure user does not see any ugly stack trace and redirect the user to some appropriate page based on an exception or a server fault such as 404 not found in a Java web application that uses jsp?
Upvotes: 1
Views: 735
Reputation: 23800
There are few ways to achieve this.
In the web.xml you can have something like this for example:
<error-page>
<error-code>404</error-code>
<location>/notFoundError.jsp</location>
</error-page>
So whenever the server can not find the requested resource, the user will be redirected to the given page. You can also handle Exceptions like this, again in the web.xml
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/someOtherPage.jsp</location>
</error-page>
And you can handle all exceptions by:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/errorPage.jsp</location>
</error-page>
Also, in the jsp file itself you can have a JSP directive like this, that will override anything in web.xml:
<%@ page errorPage="errorpage.jsp" %>
This means if anything goes wrong in the jsp, errorpage.jsp will be loaded. errorpage.jsp will also need a directive in it as follows, so that pageWithError.jsp can actually be forwarded to errorpage.jsp:
<%@ page isErrorPage="true" %>
So if you have the directive in the jsps(both the page that has the error, and the page that will be shown in case of an error), that will be taken into account. If not, and some error happens, web.xml will be consulted. Still no matches? Well then a 404 or a stacktrace will be shown..
Directive in the jsp is like overriding web.xml.
Hope it helps!!!
Upvotes: 2