Web开发中错误页面的配置

一、创建错误处理页。

1)web.xml里面添加

<error-page>
<error-code>404</error-code>
<location>/404.html</location>
 </error-page>  

2)在根目录下建立404.html

3)测试:随手输入一个不存在的url地址。可以看到404.html被正确显示。

二、按异常类型指定跳转。 

1)新建servlet包的Hello.java

2)在doGet里添加

PrintWriter out=resp.getWriter();//此为servlet的输出对象
Object obj = null;
out.println(obj.toString()); //会出现java.lang.NullPointerException异常

另附上完整java代码:

package servlet;

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 hello extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out=response.getWriter();
		out.println(", using the POST method");
		Object obj = null;
		out.println(obj.toString());   

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);

	}

}

3)在根目录下建立error.html

4)在web.xml中添加

<!-- servlet配置 -->
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>servlet.hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/servlet/hello</url-pattern>
  </servlet-mapping><!-- error-page配置 -->
  <error-page>
  <exception-type>java.lang.NullPointerException</exception-type>  <!--异常类型-->
  <location>/error.html</location>  

5)测试:在地址栏中输入http://localhost:8080/ProjectTest/servlet/hello

web.xml配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	  <display-name></display-name>	

   <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>servlet.hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/servlet/hello</url-pattern>
  </servlet-mapping>
  <!-- error-page配置开始 -->
  <error-page>
  <exception-type>java.lang.NullPointerException</exception-type>  <!--异常类型-->
  <location>/error.html</location>
</error-page>
<!-- error-page配置结束 --> 

 <!-- 404页面配置 开始-->
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<!-- 404页面配置 结束-->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
上一篇:Java集合(3)一 红黑树、TreeMap与TreeSet(上)


下一篇:Java程序员学C#基本语法两个小时搞定(对比学习)