I am using Tomcat. I defined some
in web.xml
and mapped 404
error to page /error/error.jsp
. I need to
Just use HttpServletResponse#sendError() with a status code. E.g.
File resource = new File(path, name);
if (!resource.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // Sends 404.
return;
}
The servletcontainer will then display the suitable errorpage.
Note: the return
statement isn't there for decoration. It will avoid that the remant of the code in the same method block will continue to run and might produce IllegalStateException
s in the appserver logs! Starters namely often think that methods like sendRedirect()
, forward()
, sendError()
, etc somehow automagically exits the method block when invoked. This is thus not true ;)