unico modo per gestire in modo generico è quello di utilizzare web.xml
come di seguito:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/ErrorHandler</location>
</error-page>
Il servlet è gettato ServletException
e IOException
, ma se si vuole gestire le eccezioni di runtime e di tutte le altre eccezioni in una sola eccezione gestore, è possibile fornire un tipo di eccezione come Throwable
. È possibile utilizzare più voci della pagina di errore che gestiranno tipi diversi di eccezioni e avranno gestori diversi.
Esempio:
@WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//customize error message
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
request.setAttribute("error", "Servlet " + servletName +
" has thrown an exception " + throwable.getClass().getName() +
" : " + throwable.getMessage());
request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
}
}
fonte
2014-11-07 13:15:06
duplicati di http://stackoverflow.com/q/7066192 Performing in avanti() come nel tuo snippet e nella risposta che segue è di almeno sbagliata. Se vuoi davvero farlo a livello di codice, dovresti usare sendError(), non forward(). – BalusC