I am using Tomcat. I defined some
in web.xml
and mapped 404
error to page /error/error.jsp
. I need to
No, there is no API. The setting is internal to Tomcat, it doesn't expose this to the outside world directly. (You can, as you said, parse the web.xml - since it's XML it would be simple to write an XQuery to pull this out).
Also I think you seem to be confused as to exactly how this is supposed to work. You supply a URI to Tomcat that it will use to serve the HTML body of a 404 response. It will need to be able to resolve this URI into an actual resource just as if it were supplied in a request. So in many cases, you don't need a servlet to detect if the resource exists - you need a servlet to contain the resource to be served. The exception being if you use Tomcat to serve static filesystem data for some URLs, which I believe is possible albeit seldom used.
If you have a Tomcat set up without any servlets, what are you expecting it to serve anyway? Where on earth are you expecting it to get your error.jsp
page from? How do you expect it to know that? What you need to do is add at least one servlet to Tomcat (containing the error.jsp
file), and then make sure that web.xml maps the /error/error.jsp
URL to this servlet (and that the resource is positioned in the error subdirectory in the servlet).
Once this is done, you should be able to manually go to e.g. http://localhost:8080/<context>/error/error.jsp
and have the response served (possibly with some weird content since there's no actual exception but the file should be found). Similarly, if you've set up the error-page directive correctly in web.xml, going to an umapped URL (e.g. http://localhost:8080/<context>/asdfghjasgh
) should show you your error page as the 404 response.
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 ;)