View Javadoc

1   package com.atlassian.johnson.spring.lifecycle;
2   
3   import com.atlassian.johnson.spring.web.context.support.JohnsonHttpRequestHandlerServlet;
4   
5   import javax.annotation.Nonnull;
6   import javax.servlet.ServletException;
7   import javax.servlet.http.HttpServletRequest;
8   import javax.servlet.http.HttpServletResponse;
9   import java.io.IOException;
10  
11  /**
12   * A specialized {@link JohnsonHttpRequestHandlerServlet} for use with the {@link LifecycleDispatcherServlet}. This
13   * servlet automatically redirects to the error page when requests are received during application startup.
14   *
15   * @since 3.0
16   */
17  public class LifecycleHttpRequestHandlerServlet extends JohnsonHttpRequestHandlerServlet {
18  
19      private volatile boolean starting = true;
20  
21      @Override
22      public void init() throws ServletException {
23          LifecycleState state = LifecycleUtils.getCurrentState(getServletContext());
24          if (state == LifecycleState.STARTED) {
25              starting = false;
26  
27              super.init();
28          }
29      }
30  
31      @Override
32      protected void service(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response)
33              throws ServletException, IOException {
34          if (starting) {
35              if (LifecycleUtils.isStarting(getServletContext())) {
36                  //Otherwise, if the application is still starting, redirect the request to the error page
37                  sendRedirect(response);
38  
39                  return;
40              } else {
41                  //The first time we see a status other than CREATED or STARTING, note that the application
42                  //is no longer starting and service the request normally
43                  starting = false;
44              }
45          }
46  
47          super.service(request, response);
48      }
49  }