Java web的几种异常处理

.在servlet容器中处理异常

以下两种方式:

1. 在web.xml定义异常处理

如果没有在web的应用中作异常处理,那么异常就会抛给Servlet容器,应该说此时Servlet容器是处理异常的时机了。如果此时Servlet容器还不对异常处理的话,那么容器会把异常的内容直接显示给访问者。 Servlet容器通过web.xml配置对异常的处理。在web.xml中进行异常处理的配置是通过 元素来表示,支持两种类型的异常拦截。

1)依据http请求所返回的状态码来拦截

2)通过java异常类的类型来进行拦截

如下两种类型的实例

404

/errors/pageNoFound.jsp

java.lang.NullPointerException

/errors/pageNoFound.jsp

错误页面中错误信息的显示

从jsp2.0开始,除了在错误页面中可以使用绑定到request的exception对象外,还增加了一个名为errorData的绑定到pageContext的对象。它是javax.servlet.jsp.ErrorData类的对象。

errorData的属性

-------------------------------------------------------

属性 类型 描述

requestURI String 发出请求失败的URI

servletName String 发生错误的servlet或jsp页面的名称

statusCode int 发生错误的状态码

throwable Throwable 导致当前错误的异常

--------------------------------------------------------

在错误页面中,可用如下实例显示错误信息

<%@ page isErrorPage="true" contentType="text/html"; charset="utf-8" %>

...

请求地址:${pageContext.errorData.requestURI}

状态码: ${pageContext.errorData.statusCode}

异常: ${pageContext.errorData.throwable}

注:某些版本的浏览器需要关闭“显示友好http错误信息”功能才能正常显示错误信息。“工具”->"internet选项"->高级

2.自定义异常页面(在jsp页面中定义)

通过jsp页面中@page 的errorPage属性来进行,如下:

<% page errorPage="errors/error.jsp" %>

这种处理方式将会覆盖在web.xml中的定义 自定义异常将会拦截所有的异常,也就是说不能依据不同的异常的类型来进行不同的处理(区别于servlet容器异常处理)

二.Struts的异常处理机制
以下三种方式
1.编程式处理异常手动处理

a)在发生异常的地方创建异常信息,并抛出异常

b)捕获异常,传递异常信息到相应的异常处理页面

c)在Struts的配置文件struts-config.xml中,相应的action中配置 指定异常处理页面

d)异常处理jsp页面中显示信息

e)国际化资源文件ApplicationResources_zh_CN.properties中加入key-value

具体实例如下:

a)抛出异常

public void delOrg(int orgId) {

Orgnization org=(Orgnization)getHibernateTemplate().load(Orgnization.class, orgId);

if(org.getChildren().size()>0)

{

//抛出异常信息

throw new RuntimeException("存在子机构,不允许删除");

}

getHibernateTemplate().delete(org);

}

b)捕获异常,传递异常信息(此函数调用上一步定义的函数delOrg)

public ActionForward del(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

OrgActionForm oaf = (OrgActionForm)form;

try {

orgManager.delOrg(oaf.getId());

} catch (Exception e) {

//创建国际化文本信息

ActionMessages msgs=new ActionMessages();

ActionMessage msg=new ActionMessage("errors.detail",e.getMessage());

msgs.add("detail", msg);

//传递国际化文本信息

this.saveErrors(request, msgs);

return mapping.findForward("exception");

}

return mapping.findForward("pub_add_success");

}

c)在Struts的配置文件struts-config.xml中,相应的action中配置 指定异常处理页面

path="/org"

type="org.springframework.web.struts.DelegatingActionProxy"

name="orgForm"

scope="request"

parameter="method"

>

d)/org/exception.jsp中显示异常信息

可以用 显示异常信息。

e)国际化资源文件ApplicationResources_zh_CN.properties中加入

errors.detail={0}

注:{0}表示接收的第一个参数。

2.自动异常处理方式(只能处理带一个参数的情况)

a)在发生异常的地方创建异常信息,并抛出异常

b)在Struts的配置文件struts-config.xml中,相应的action中配置

c)异常处理jsp页面中显示信息

d)国际化资源文件ApplicationResources_zh_CN.properties中加入key-value

此方式比上一种方式(编程式)少了"捕获异常"的步骤,在strtus-config.xml中的配置也有所不同。

在struts-config.xml的配置如下:

path="/org"

type="org.springframework.web.struts.DelegatingActionProxy"

name="orgForm"

scope="request"

parameter="method"

>

3.统一的自定义异常处理

多个action使用同一个exception,将exception配置在全局exception中。mapping.findException方法会先到action中找局部exception,若没有就会找全局exception相对应前面2中方式,这种方式将所有的异常统一处理

a)自定义的异常类com.hq.exception.SystemException

b)自定义的异常处理类com.hq.exception.SystemExceptionHandler

c)struts-config.xml配置全局的exception

d)在国际资源文件ApplicationResources_zh_CN.properties中加入key-value

e)在发生异常的地方创建异常信息,并抛出异常

f)异常处理jsp页面中显示信息

a)自定义异常类com.hq.exception.SystemException

package com.hq.exception;

public class SystemException extends RuntimeException {

private String key;

private Object[]values;

public String getKey() {

return key;

}

public Object[] getValues() {

return values;

}

public SystemException() {

super();

}

public SystemException(String message, Throwable throwable) {

super(message, throwable);

}

public SystemException(String message) {

super(message);

}

public SystemException(Throwable throwable) {

super(throwable);

}

public SystemException(String key,String message)

{

super(message);

this.key=key;

}

public SystemException(String key,Object value,String message)

{

super(message);

this.key=key;

this.values=new Object[]{value};

}

public SystemException(String key,Object[] values,String message)

{

super(message);

this.key=key;

this.values=values;

}

}

b)自定义异常处理类com.hq.exception.SystemExceptionHandler

package com.hq.exception;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

import org.apache.struts.action.ExceptionHandler;

import org.apache.struts.config.ExceptionConfig;

public class SystemExceptionHandler extends ExceptionHandler {

@Override

public ActionForward execute(Exception ex, ExceptionConfig ae,

ActionMapping mapping, ActionForm formInstance,

HttpServletRequest request, HttpServletResponse response)

throws ServletException {

ActionForward forward=null;

ActionMessage error=null;

if(ae.getPath()!=null)

{

forward=new ActionForward(ae.getPath());

}else

{

forward=mapping.getInputForward();

}

if(ex instanceof SystemException)

{

SystemException se=(SystemException)ex;

String key=se.getKey();

if(key==null)

{

error=new ActionMessage(ae.getKey(),se.getMessage());

}

else

{

if(se.getValues()!=null)

{

error=new ActionMessage(key,se.getValues());

}

else

{

error=new ActionMessage(key);

}

}

this.storeException(request, key, error, forward, ae.getScope());

return forward;

}

else

{

return super.execute(ex, ae, mapping, formInstance, request, response);

}

}

}

c)struts-config.xml配置全局的exception

key="errors.detail"

type="com.hq.exception.SystemException"

path="/common/exception.jsp"

handler="com.hq.exception.SystemExceptionHandler">

上面的key指定properties资源文件中的key值,type指定异常类,handler指定异常的处理类(若没给出就会采用默认的ExceptionHandler)

d)在国际资源文件ApplicationResources_zh_CN.properties中加入key-value

errors.org.hasSubOrg=【{0}】存在{1}个子机构,不允许被删除!

e)在发生异常的地方创建异常信息,并抛出异常

public void delOrg(int orgId) {

System.out.println("delorg");

Orgnization org=(Orgnization)getHibernateTemplate().load(Orgnization.class, orgId);

if(org.getChildren().size()>0)

{

//统一异常处理

Throw new SystemException("errors.org.hassuborg",new Object[]{org.getName(),org.getChildren().size()},"存在子机构,不允许被删除");

}

getHibernateTemplate().delete(org);

}

f)异常处理jsp页面中显示信息

/common/exception.jsp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值