View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.servlet;
20  
21  import java.io.IOException;
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  import javax.servlet.ServletContext;
27  import javax.servlet.ServletException;
28  import javax.servlet.http.HttpServletRequest;
29  import javax.servlet.http.HttpServletResponse;
30  
31  import org.eclipse.jetty.http.HttpMethod;
32  import org.eclipse.jetty.server.Dispatcher;
33  import org.eclipse.jetty.server.Request;
34  import org.eclipse.jetty.server.handler.ContextHandler;
35  import org.eclipse.jetty.server.handler.ErrorHandler;
36  import org.eclipse.jetty.util.log.Log;
37  import org.eclipse.jetty.util.log.Logger;
38  
39  /* ------------------------------------------------------------ */
40  /** Error Page Error Handler
41   *
42   * An ErrorHandler that maps exceptions and status codes to URIs for dispatch using
43   * the internal ERROR style of dispatch.
44   *
45   */
46  public class ErrorPageErrorHandler extends ErrorHandler
47  {
48      private static final Logger LOG = Log.getLogger(ErrorPageErrorHandler.class);
49  
50      public final static String ERROR_PAGE="org.eclipse.jetty.server.error_page";
51      public final static String GLOBAL_ERROR_PAGE = "org.eclipse.jetty.server.error_page.global";
52  
53      protected ServletContext _servletContext;
54      private final Map<String,String> _errorPages= new HashMap<String,String>(); // code or exception to URL
55      private final List<ErrorCodeRange> _errorPageList=new ArrayList<ErrorCodeRange>(); // list of ErrorCode by range
56  
57      /* ------------------------------------------------------------ */
58      public ErrorPageErrorHandler()
59      {}
60  
61      /* ------------------------------------------------------------ */
62      /**
63       * @see org.eclipse.jetty.server.handler.ErrorHandler#handle(String, Request, HttpServletRequest, HttpServletResponse)
64       */
65      @Override
66      public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
67      {
68          String method = request.getMethod();
69          if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method))
70          {
71              baseRequest.setHandled(true);
72              return;
73          }
74          if (_errorPages!=null)
75          {
76              String error_page= null;
77              Class<?> exClass= (Class<?>)request.getAttribute(Dispatcher.ERROR_EXCEPTION_TYPE);
78  
79              if (ServletException.class.equals(exClass))
80              {
81                  error_page= (String)_errorPages.get(exClass.getName());
82                  if (error_page == null)
83                  {
84                      Throwable th= (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);
85                      while (th instanceof ServletException)
86                          th= ((ServletException)th).getRootCause();
87                      if (th != null)
88                          exClass= th.getClass();
89                  }
90              }
91  
92              while (error_page == null && exClass != null )
93              {
94                  error_page= (String)_errorPages.get(exClass.getName());
95                  exClass= exClass.getSuperclass();
96              }
97  
98              if (error_page == null)
99              {
100                 // look for an exact code match
101                 Integer code=(Integer)request.getAttribute(Dispatcher.ERROR_STATUS_CODE);
102                 if (code!=null)
103                 {
104                     error_page= (String)_errorPages.get(Integer.toString(code));
105 
106                     // if still not found
107                     if ((error_page == null) && (_errorPageList != null))
108                     {
109                         // look for an error code range match.
110                         for (int i = 0; i < _errorPageList.size(); i++)
111                         {
112                             ErrorCodeRange errCode = (ErrorCodeRange) _errorPageList.get(i);
113                             if (errCode.isInRange(code))
114                             {
115                                 error_page = errCode.getUri();
116                                 break;
117                             }
118                         }
119                     }
120                 }
121             }
122             
123             //try new servlet 3.0 global error page
124             if (error_page == null)
125             {
126                 error_page = _errorPages.get(GLOBAL_ERROR_PAGE);
127             }
128 
129             if (error_page!=null)
130             {
131                 String old_error_page=(String)request.getAttribute(ERROR_PAGE);
132                 if (old_error_page==null || !old_error_page.equals(error_page))
133                 {
134                     request.setAttribute(ERROR_PAGE, error_page);
135 
136                     Dispatcher dispatcher = (Dispatcher) _servletContext.getRequestDispatcher(error_page);
137                     try
138                     {
139                         if(dispatcher!=null)
140                         {
141                             dispatcher.error(request, response);
142                             return;
143                         }
144                         else
145                         {
146                             LOG.warn("No error page "+error_page);
147                         }
148                     }
149                     catch (ServletException e)
150                     {
151                         LOG.warn(Log.EXCEPTION, e);
152                         return;
153                     }
154                 }
155             }
156         }
157 
158         super.handle(target, baseRequest, request, response);
159     }
160 
161     /* ------------------------------------------------------------ */
162     /**
163      * @return Returns the errorPages.
164      */
165     public Map<String,String> getErrorPages()
166     {
167         return _errorPages;
168     }
169 
170     /* ------------------------------------------------------------ */
171     /**
172      * @param errorPages The errorPages to set. A map of Exception class name  or error code as a string to URI string
173      */
174     public void setErrorPages(Map<String,String> errorPages)
175     {
176         _errorPages.clear();
177         if (errorPages!=null)
178             _errorPages.putAll(errorPages);
179     }
180 
181     /* ------------------------------------------------------------ */
182     /** Add Error Page mapping for an exception class
183      * This method is called as a result of an exception-type element in a web.xml file
184      * or may be called directly
185      * @param exception The exception
186      * @param uri The URI of the error page.
187      */
188     public void addErrorPage(Class<? extends Throwable> exception,String uri)
189     {
190         _errorPages.put(exception.getName(),uri);
191     }
192 
193     /* ------------------------------------------------------------ */
194     /** Add Error Page mapping for an exception class
195      * This method is called as a result of an exception-type element in a web.xml file
196      * or may be called directly
197      * @param exceptionClassName The exception
198      * @param uri The URI of the error page.
199      */
200     public void addErrorPage(String exceptionClassName,String uri)
201     {
202         _errorPages.put(exceptionClassName,uri);
203     }
204 
205     /* ------------------------------------------------------------ */
206     /** Add Error Page mapping for a status code.
207      * This method is called as a result of an error-code element in a web.xml file
208      * or may be called directly
209      * @param code The HTTP status code to match
210      * @param uri The URI of the error page.
211      */
212     public void addErrorPage(int code,String uri)
213     {
214         _errorPages.put(Integer.toString(code),uri);
215     }
216 
217     /* ------------------------------------------------------------ */
218     /** Add Error Page mapping for a status code range.
219      * This method is not available from web.xml and must be called
220      * directly.
221      * @param from The lowest matching status code
222      * @param to The highest matching status code
223      * @param uri The URI of the error page.
224      */
225     public void addErrorPage(int from, int to, String uri)
226     {
227         _errorPageList.add(new ErrorCodeRange(from, to, uri));
228     }
229 
230     /* ------------------------------------------------------------ */
231     @Override
232     protected void doStart() throws Exception
233     {
234         super.doStart();
235         _servletContext=ContextHandler.getCurrentContext();
236     }
237 
238     /* ------------------------------------------------------------ */
239     /* ------------------------------------------------------------ */
240     private class ErrorCodeRange
241     {
242         private int _from;
243         private int _to;
244         private String _uri;
245 
246         ErrorCodeRange(int from, int to, String uri)
247             throws IllegalArgumentException
248         {
249             if (from > to)
250                 throw new IllegalArgumentException("from>to");
251 
252             _from = from;
253             _to = to;
254             _uri = uri;
255         }
256 
257         boolean isInRange(int value)
258         {
259             if ((value >= _from) && (value <= _to))
260             {
261                 return true;
262             }
263 
264             return false;
265         }
266 
267         String getUri()
268         {
269             return _uri;
270         }
271 
272         @Override
273         public String toString()
274         {
275             return "from: " + _from + ",to: " + _to + ",uri: " + _uri;
276         }
277     }
278 }