您的位置:首页 > 编程语言 > Java开发

JavaWeb前台异常处理

2010-03-02 22:39 302 查看
[align=center]JavaWeb前台异常处理[/align]

在做Java Web程序时候,如果出错了,常常会在页面上打印出错误的堆栈内存信息,在开发阶段对调试程序很有帮助,但是在运营环境下,这样的处理很不友好,非开发人员看了都会傻眼。

这里给出一个简单的处理方式,使用错误页面来处理。

一、创建两个常见的HTML错误信息页面:

404.html

<body>
所访问的资源不存在:对不起,所请求的资源不存在! <br>
</body>

500.html

<body>
服务器内部错误:对不起,服务器忙! <br>
</body>

二、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ErrServlet</servlet-name>
<servlet-class>lavasoft.errtest.ErrServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ErrServlet</servlet-name>
<url-pattern>/servlet/ErrServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.html</location>
</error-page>
</web-app>

三、创建一个测试的Servlet,用来抛500错误的用的,呵呵。

package lavasoft.errtest;

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
throw new RuntimeException("------");
}
}

四、测试

1、当访问不存在的资源时候,服务器会返回404错误状态,这样会自动转向404对应的错误页面404.html,将其发送给客户端。

2、当服务器处理错误时候,会返回500错误状态码,这样自动转向500对应的错误页面500.html,将其发送给客户端。

这样,不费多大劲,就把异常的不友好问题解决了!
当然,这仅仅是最简单的最懒惰的一种处理方式,还有一种方式值得推荐:那就是在有好提示的页面不直接显示错误堆栈信息,只有当请求查看错误详细信息时候才点击才显示出来,这个效果是通过js实现的。本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/280019
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: