Struts2的异常映射.docVIP

  • 3
  • 0
  • 约5.4千字
  • 约 6页
  • 2017-05-12 发布于河南
  • 举报
Struts2的异常映射

Struts2的异常映射 5.5? Struts2的异常映射 5.5.1??异常映射基础 在Action中execute方法的方法签名为public String execute() throws Exception,这样,Action可以抛出任何Exception,那么,Exception抛给谁呢? 1:自己实现异常处理 来做一个简单的试验,在Action的方法中这样写: ? java代码: 查看复制到剪贴板打印 public?String?execute()?throws?Exception?{?? ????????int?a?=?5/0;?? ????????return?this.SUCCESS;?? }?? 上面的代码中有int a=5/0;,很显然,会抛出除数为0的错误,这个错误是RuntimeException,我们的程序没有进行相应的例外处理,则会抛给Struts2去处理。运行结果如下图所示: 图5.3? 报例外的页面 可见,这个错误直接被抛给了web容器,Struts2并没有处理。那么,在实际的项目中很显然不能这么简单而粗暴的处理错误,一种简单的处理方法就是跳转到一个错误处理页面。 ?????? 假设要求这个Action,在出现“ArithmeticException”的时候,跳转到一个叫math-exception的Result,而其他错误跳转到另一个叫otherwise-exception的Result。那么,在Action中可以这么写。 ? java代码: 查看复制到剪贴板打印 public?String?execute()?throws?Exception?{?? ????try?{?? ????????int?a?=?5/0;?? ????}?catch?(ArithmeticException?e)?{?? ????????e.printStackTrace();?? ????????return?math-exception;?? ????}?catch?(Exception?e){?? ????????e.printStackTrace();?? ????????return?otherwise-exception;?? ????}?? ????return?success;?? }?? 这样,在运行中出现ArithmeticException就会跳转到math-exception指定的页面,而其他Exception就会跳转到otherwise-exception指定的页面,如果没有出错,就会跳转到success指定的页面。 在struts.xml的Action中,只要配置好上述三个Result就可以正常运行了。 2:使用Struts2的异常机制 ?????? 介绍到这里,我们还没有接触Struts2的异常机制,只是把Struts2的异常机制要做的事情,自己用编码实现了一遍。下面,来看看如何使用Struts2的异常机制。 ?????? 在action元素中设置exception-mapping元素,可以指定在execute方法抛出指定错误的时候,跳转到哪个指定的页面。 ?????? 修改上面的代码,使用Struts2的异常机制就不需要自己手动去try-catch了,Action的代码还原为如下所示: ? java代码: 查看复制到剪贴板打印 public?String?execute()?throws?Exception?{?? ????????int?a?=?5/0;?? ????????return?this.SUCCESS;?? }?? ? ? ? ?然后在struts.xml的action元素中增加exception-mapping子元素,示例如下: ? java代码: 查看复制到剪贴板打印 action?name=helloworldAction?class=cn.javass.action.action.HelloWorldAction?? ????exception-mapping?result=math-exception?exception=java.lang.ArithmeticException/?? ????exception-mapping?result=math-exception?exception=java.lang.Exception/?? ????result?name=math-exception/error.jsp/result?? ????result/s2impl/welcome.jsp/result?? /action?? 在action元素里面,增加了两个exception-mapping元素,其execption属性指定了一个Excepti

文档评论(0)

1亿VIP精品文档

相关文档