1

How do I generate error pages dynamically instead of serving static pages? Or is this impossible?

I am working on my first Java Web App and I am trying to learn the intricacies of the web.xml configuration file. My understanding based on the documentation is that error pages are configured by specifying a static file to be served for a given HTTP status code or Java exception. For example...

This would serve a page for internal server errors

...
<error-page>
    <error-code>500</error-code>
    <location>/errors/http/500.html</location>
</error-page>
...

This would serve a page for servlet exceptions

...
<error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/errors/java/servlet_exception.html</location>
</error-page>
...

This would specify a default error page for everything

...
<error-page>
    <location>/errors/index.html</location>
</error-page>
...

But how do I send this information to a script/class?

I want my error pages to be pretty standard. Maybe include a logo, the error code, and a brief message based on the error. I would like the status code or exception type to be passed as parameters to the script/class. Is there any way to do this?

Community
  • 1
  • 1
William Rosenbloom
  • 2,506
  • 1
  • 14
  • 37
  • Do not include data about Exceptions (or anything else that can identity the server/framework you're using) on any page. This is a security risk which would provide key data to hackers about your system architecture, etc. – Andrew S Aug 16 '16 at 21:32
  • @AndrewS Thank you for the reminder but I have clearly stated that I am using a Java Web App, so isn't it a fair assumption that I would be using `javax.servlet`? I didn't feel like that would be giving away much. – William Rosenbloom Aug 16 '16 at 22:48

1 Answers1

1

Basically you need to:

  1. setup an error-page as a servlet or jsp (the "error handler")
  2. within your error handler you will get several data, describing the error, as request attribute. Example: let's say you configure your web.xml with 2 directives to handle 404 status codes and java.lang.IllegalArgumentException exceptions.

When you cause a 404, the error handler will see the following request attributes:

javax.servlet.forward.request_uri /testwebapp1/errordd 
javax.servlet.forward.context_path /testwebapp1 
javax.servlet.forward.servlet_path /errordd 
javax.servlet.forward.path_info /error 
javax.servlet.error.message /testwebapp1/errordd 
javax.servlet.error.status_code 404 
javax.servlet.error.servlet_name default 
javax.servlet.error.request_uri /testwebapp1/errordd 

javax.servlet.error.status_code contains the http status code

If you cause an IllegalArgumentException, the request attributes will contain an attribute "javax.servlet.error.exception_type" with the raised exception. More details about these constants can be found here https://tomcat.apache.org/tomcat-7.0-doc/servletapi/constant-values.html

teroplut
  • 131
  • 2
  • 5