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-name> ErrorHandler </ servlet-name>
        <Servlet-class> ErrorHandler </ servlet-class>
</ Servlet>
<-! Servlet mapping ->
        <Servlet-name> ErrorHandler </ servlet-name>
        <Url-pattern> / ErrorHandler </ url-pattern>
</ Servlet-mapping>

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

<-! Exception-type related error page ->
    </ Exception-type>
    <Location> / ErrorHandler </ location>
</ Error-page>

    <Exception-type> </ 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:

    <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.

序号属性 & 描述
该属性给出状态码,状态码可被存储,并在存储为 java.lang.Integer 数据类型后可被分析。
该属性给出异常类型的信息,异常类型可被存储,并在存储为 java.lang.Class 数据类型后可被分析。
该属性给出确切错误消息的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。
该属性给出有关 URL 调用 Servlet 的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。
该属性给出异常产生的信息,信息可被存储,并在存储为 java.lang.Throwable 数据类型后可被分析。
该属性给出 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 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)
		Integer statusCode = (Integer)
		String servletName = (String)
		if (servletName == null){
			servletName = "Unknown";
		String requestUri = (String)
		if (requestUri == null){
			requestUri = "Unknown";
		// 设置响应内容类型
		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");
	   	if (throwable == null && statusCode == null){
	      	out.println("请返回 <a href=\"" + 
	        response.encodeURL("../../localhost:8080/index.html") + 
	   	}else if (statusCode != null) {
	      	out.println("错误代码 : " + statusCode);
	      	out.println("Servlet Name : " + servletName + 
	      	out.println("异常类型 : " + 
	                          throwable.getClass( ).getName( ) + 
	      	out.println("请求 URI: " + requestUri + 
	      	out.println("异常信息: " + 
	                              throwable.getMessage( ));
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request,
	                  HttpServletResponse response)
	   throws ServletException, IOException {
		doGet(request, response);

The usual way to, 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"?>  
<!-- servlet mappings -->
    <exception-type>java.lang.Throwable</exception-type >

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: