http://hi.baidu.com/xogjghsfhjemorr/item/5aab56f5f2f220ed1b111f5c

来源:互联网 发布:免费胸卡制作软件 编辑:程序博客网 时间:2024/06/07 07:00

将Struts的Action方法中抛出的Exception信息显示在页面上的方法

  

 

1、定义一个ExceptionHandlerApp类,继承org.apache.struts.action.ExceptionHandler;


2、在ExceptionHandlerApp类中的execute方法中,将错误的Message写入attribute,并且处理发生错误时候,定向的错误页面。
如下:
 public ActionForward execute(Exception ex, ExceptionConfig exCfg,
   ActionMapping mapping, ActionForm form, HttpServletRequest request,
   HttpServletResponse response) throws ServletException {
  
  log.info("Error Catched by ExceptionHandlerImpl,Ex="
    + ex.getMessage());
  request.setAttribute("error",ex.getMessage());

  return mapping.findForward("error");
 }


3、在struts配置文件中,加入处理标签。如果多个模块的struts应用系统,据试验应该在每个模块中都放置该标签,而不能仅仅在struts-config.xml中添加(好像这个文件,没多大用了)
 struts-user-config.xml中,添加:
 <global-exceptions>
     <exception
       key="error"
       type="java.lang.Exception"
       handler="com.lovefanx.framework.web.ExceptionHandlerImpl"/>
 </global-exceptions>

4、在这个配置文件中struts-user-config.xml中,加入发生错误后,要显示的页面。
  <global-forwards>
   <forward name="error" path="/../error/error.jsp"/>
  </global-forwards>


5、现实的错误界面error.jsp
<table width="50%" align="center" border="1">
 <tr>
  <td>系统错误信息:</td>
 </tr>
 <tr>
  <td><bean:write name="error" /></td>
 </tr>
</table>


6、Action类中的方法,不需要try--catch--,如果遇到抛出错误,会直接抛出,并且交给handler="com.lovefanx.framework.web.ExceptionHandlerImpl"处理。


7、如果struts使用spring+hibernate一起构建系统,那么spring的service类,建议将可能遇到的错误,抛出Exception即可,交给struts的action处理。而hibernate实现类,可以考虑不用处理exception了,这样比较简单。