简体   繁体   中英

Tomcat - Redirect to Error Page when ServletContextListener fails

When Tomcat starts it calls my ServletContextListener to obtain a database connection, which I will later use in other servlets with getServletContext(). It is called in my web.xml as:
listener
listener-class org.ppdc.database.DBCPoolingListener /listener-class
/listener>
listener
listener-class org.ppdc.database.DBCPoolingListener /listener-class
/listener>
(I removed the < > because they wouldn't display properly in this message.>

If I cannot connect to the database when Tomcat starts up I get a 404 error, because Tomcat cannot start the application.

How can I redirect the user to a custom error page at this point? I tried the following in my web.xml (I have the < > brackets in the original):
(error-page)
(error-code404/error-code)
(location/file_not_found.html/location)
(/error-page)

Any ideas on how to redirect a user to one of my error pages when Tomcat tries to start the application?

Thanks Vic

If your application fails to load, then that's it. Tomcat is not running it and does not serve your error-pages.

So, if you want to handle a half-dead state, you need to start in a half-dead state. Fortunately, the code in your servlets can be spared checks whether the app is half-dead if you install a Filter, that does it before control is transfered to any servlet.

Declare a filter in web.xml:

<filter>
  <filter-name>IsHalfDeadFilter</filter-name>
  <filter-class>my.package.IsHalfDeadFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>IsHalfDeadFilter</filter-name>
  <url-pattern>*</url-pattern>
</filter-mapping>

Then implement doFilter method to redirect to your error page.

@Override
public void doFilter (
        final ServletRequest request,
        final ServletResponse response,
        final FilterChain chain
    ) throws
        IOException,
        ServletException
{
    if ( isHalfDead )
    {
        // redirect to error page
        return;
    }

    chain.doFilter( request, response );
}

Read more about Filters here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM