Latest web development tutorials

Servlet Exception Handling

When a Servlet throws an exception, Web container used in the search for exception-type elementin web.xml and thrown matches the type of configuration.

You must use theerror-page element in web.xml to specify accordingly Servlet calls to specific exceptionsor HTTPstatus code.

web.xml Configuration

Suppose there's aErrorHandlerServelt is called when any unusual or defined errors. The following items will be created in web.xml.

<-! Servlet definitions ->
<Servlet>
        <Servlet-name> ErrorHandler </ servlet-name>
        <Servlet-class> ErrorHandler </ servlet-class>
</ Servlet>
<-! Servlet mapping ->
<Servlet-mapping>
        <Servlet-name> ErrorHandler </ servlet-name>
        <Url-pattern> / ErrorHandler </ url-pattern>
</ Servlet-mapping>

<-! Error-code-related error page ->
<Error-page>
    <Error-code> 404 </ error-code>
    <Location> / ErrorHandler </ location>
</ Error-page>
<Error-page>
    <Error-code> 403 </ error-code>
    <Location> / ErrorHandler </ location>
</ Error-page>

<-! Exception-type related error page ->
<Error-page>
    <Exception-type>
          javax.servlet.ServletException
    </ Exception-type>
    <Location> / ErrorHandler </ location>
</ Error-page>

<Error-page>
    <Exception-type> java.io.IOException </ exception-type>
    <Location> / ErrorHandler </ location>
</ Error-page>

If you want all exceptions have a generic error handler, you should define the following error-page, rather than define separate exception error-page element for each:

<Error-page>
    <Exception-type> java.lang.Throwable </ exception-type>
    <Location> / ErrorHandler </ location>
</ Error-page>

The following are points on the above web.xml exception handling is to be noted:

  • Servelt ErrorHandler with other Servelt defined the same way, and is configured in web.xml.
  • If there is an error status code appears regardless of the 404 (Not Found Not Found) or 403 (Forbidden ban), ErrorHandler the Servlet will be invoked.
  • If the Web application orServletExceptionthrowsIOException,then the Web container will call ErrorHandler the Servlet.
  • You can define different error handler to handle different types of errors or exceptions. The above example is very versatile, I hope you understand the basic concepts through examples.

Request Properties - error / exception

The following is a list of request attributes Servlet error handling can be accessed, used to analyze the nature of the error / exception.

序号属性 & 描述
1javax.servlet.error.status_code
该属性给出状态码,状态码可被存储,并在存储为 java.lang.Integer 数据类型后可被分析。
2javax.servlet.error.exception_type
该属性给出异常类型的信息,异常类型可被存储,并在存储为 java.lang.Class 数据类型后可被分析。
3javax.servlet.error.message
该属性给出确切错误消息的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。
4javax.servlet.error.request_uri
该属性给出有关 URL 调用 Servlet 的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。
5javax.servlet.error.exception
该属性给出异常产生的信息,信息可被存储,并在存储为 java.lang.Throwable 数据类型后可被分析。
6javax.servlet.error.servlet_name
该属性给出 Servlet 的名称,名称可被存储,并在存储为 java.lang.String 数据类型后可被分析。

Servlet error handler instance

The following are examples of Servlet, will deal with any errors in your error handler defined or when an exception occurs.

This example allows you to Servlet Exception handling a basic understanding, you can use the same concept to write more complex exception handling applications:

//导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

//扩展 HttpServlet 类
public class ErrorHandler extends HttpServlet {

	// 处理 GET 方法请求的方法
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		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";
		}
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");
	
		PrintWriter out = response.getWriter();
		String title = "本教程 Error/Exception 信息";
	   
		String docType = "<!DOCTYPE html>\n";
		out.println(docType +
	    	"<html>\n" +
	     	"<head><title>" + title + "</title></head>\n" +
	     	"<body bgcolor=\"#f0f0f0\">\n");
	   	out.println("<h1>本教程异常信息实例演示</h1>");
	   	if (throwable == null && statusCode == null){
	      	out.println("<h2>错误信息丢失</h2>");
	      	out.println("请返回 <a href=\"" + 
	        response.encodeURL("../../localhost:8080/index.html") + 
	        	"\">主页</a>。");
	   	}else if (statusCode != null) {
	      	out.println("错误代码 : " + statusCode);
		}else{
		   	out.println("<h2>错误信息</h2>");
	      	out.println("Servlet Name : " + servletName + 
	                          "</br></br>");
	      	out.println("异常类型 : " + 
	                          throwable.getClass( ).getName( ) + 
	                          "</br></br>");
	      	out.println("请求 URI: " + requestUri + 
	                          "<br><br>");
	      	out.println("异常信息: " + 
	                              throwable.getMessage( ));
	   	}
	   	out.println("</body>");
	   	out.println("</html>");
	}
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request,
	                  HttpServletResponse response)
	   throws ServletException, IOException {
		doGet(request, response);
	}
}

The usual way to compileErrorHandler.java, put your class files in <Tomcat-installation-directory> / webapps / ROOT / WEB-INF / classes in.

Let's add the following configuration in the web.xml file to handle exceptions:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<servlet>
        <servlet-name>ErrorHandler</servlet-name>
        <servlet-class>com.w3big.test.ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
        <servlet-name>ErrorHandler</servlet-name>
        <url-pattern>/TomcatTest/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
    <error-code>404</error-code>
    <location>/TomcatTest/ErrorHandler</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>
</web-app>  

Now, try to use a produce abnormal Servlet, or enter an erroneous URL, which will trigger the Web container invokesErrorHandler the Servlet, and displays the appropriate message.For example, if you enter a wrong URL (eg: http: // localhost: 8080 / TomcatTest / UnKonwPage), it displays the following results: