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?
1 Answers
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!!!

- 22,894
- 45
- 188
- 319
-
Can you post the same answer in [duplicate one](http://stackoverflow.com/questions/7066192/how-to-specify-the-default-error-page-in-web-xml) as well that might help others. or link this answer. It will increase the probability to read your answer. – Braj Jul 13 '14 at 10:57
-
@Braj That question is about defining error pages in web.xml and about errors. My question is about Exceptions and how to handle them in jsp files. – Koray Tugay Jul 13 '14 at 11:05
-
@Braj You can answer this question if you want to help me: http://stackoverflow.com/questions/24721418/what-is-the-difference-between-expression-language-functions-and-custom-tags – Koray Tugay Jul 13 '14 at 11:06