Servlet如何编写异常呢?

Java-教程王 Servlet 发布时间:2021-08-13 09:39:58 阅读数:16810 1
下文讲述常见的Servlet抛出异常的处理方法分享,
实现思路:
    1.在web.xml中的exception-type定义相应的异常类型及所对应的处理Servlet
    2.在web.xml中使用error-page设置相应的状态码对应的Servlet
例: 使用 ExceptionHandler Servlet处理异常的Servlet

<!-- servlet 定义 -->
<servlet>
        <servlet-name>ExceptionHandler</servlet-name>
        <servlet-class>com.java265.ExceptionHandler</servlet-class>
</servlet>
<!-- servlet 映射 -->
<servlet-mapping>
        <servlet-name>ExceptionHandler</servlet-name>
        <url-pattern>/com.java265.ExceptionHandler</url-pattern>
</servlet-mapping>

<!-- error-code 相关的错误页面 -->
<error-page>
    <error-code>404</error-code>
    <location>/ExceptionHandler</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/ExceptionHandler</location>
</error-page>

<!-- exception-type 相关的错误页面 -->
<error-page>
    <exception-type>
          javax.servlet.ServletException
    </exception-type >
    <location>/ExceptionHandler</location>
</error-page>

<error-page>
    <exception-type>java.io.IOException</exception-type >
    <location>/ExceptionHandler</location>
</error-page>

exception-type注意事项:
    java.lang.Throwable可以接收所有异常类型
--------------------------------------
 如:想配置所有异常所对应的Servlet
 
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ExceptionHandler</location>
</error-page>
 
当我们在web.xml中采用以上配置后,
 无论异常还是 403,500,404等状态码,
都会调用 ExceptionHandler Servlet进行相应的处理
例:

ServletHelloWorld.java

package servlet01;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletHelloWorld extends HttpServlet {

	private static final long serialVersionUID = 888;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.sendError(500, "Server Exception!");
 
	}

}



ExceptionHandler.java

package servlet01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExceptionHandler extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub

		Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
		String servletName = (String) req.getAttribute("javax.servlet.error.servlet_name");
		if (servletName == null) {
			servletName = "Unknown";
		}
		String requestUri = (String) req.getAttribute("javax.servlet.error.request_uri");
		if (requestUri == null) {
			requestUri = "Unknown";
		}
		// 设置响应内容类型
		resp.setContentType("text/html;charset=UTF-8");

		PrintWriter out = resp.getWriter();
		String title = "Java265教程 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>Java265教程异常信息实例演示</h1>");
		if (throwable == null && statusCode == null) {
			out.println("<h2>错误信息丢失</h2>");
			out.println("请返回 <a href=\"" + resp.encodeURL("http://localhost:8080/servlet01") + "\">主页</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>");
	}

}



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>servlet01</display-name>
   
 <servlet>
        <servlet-name>helloWorld</servlet-name>
        <servlet-class>servlet01.ServletHelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>helloWorld</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
 
 <servlet>
        <servlet-name>ErrorHandler</servlet-name>
        <servlet-class>servlet01.ExceptionHandler</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ErrorHandler</servlet-name>
        <url-pattern>/ErrorHandler</url-pattern>
    </servlet-mapping>




<!-- error-code 相关的错误页面 -->
<error-page>
    <error-code>404</error-code>
    <location>/ErrorHandler</location>
</error-page>
<error-page>
    <error-code>403</error-code>
    <location>/ErrorHandler</location>
</error-page>

<error-page>
    <error-code>500</error-code>
    <location>/ErrorHandler</location>
</error-page>

<!-- exception-type 相关的错误页面 -->
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page> 

</web-app>


运行效果如下图所示:
Servlet异常统一处理中心
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/Servlet/202108/190.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者