• Java web的几种异常处理 (转)


    .servlet容器中处理异常

    以下两种方式:

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

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

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

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

       如下两种类型的实例

       <error-page>

          <error-code>404</error-code>   

             <location>/errors/pageNoFound.jsp</location>

       </error-page>

      

       <error-page>

           <exception-type>java.lang.NullPointerException</exception-type>

              <location>/errors/pageNoFound.jsp</location>

       </error-page>

      

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

       从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" %>

    <html>

       <head> ...</head>

       <body>

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

           状态码:  ${pageContext.errorData.statusCode} <br>

           异常: ${pageContext.errorData.throwable}  <br>

       </body>

    </html>

     

    注:某些版本的浏览器需要关闭“显示友好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中配置<forward>指定异常处理页面

      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中配置<forward>指定异常处理页面

         <action-mappings >

                  <action

                         path="/org"

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

                         name="orgForm"

                         scope="request"

                         parameter="method"

                   >

                         <forward name="index" path="/org/index.jsp" />

                         <forward name="exception" path="/org/exception.jsp" />

                  </action>

          </action-mappings>

            

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

             可以用<html:errors>显示异常信息。

            

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

             errors.detail={0}

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

     

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

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

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

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

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

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

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

       <action-mappings >

                  <action

                         path="/org"

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

                         name="orgForm"

                         scope="request"

                         parameter="method"

                  >

                    <exception key="errors.detail" type="java.lang.RuntimeException"        path="/org/exception.jsp" />

                    <forward name="index" path="/org/index.jsp" />

                  </action>

       </action-mappings >

      

      

    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

             <global-exceptions>

             <exception

              key="errors.detail"

              type="com.hq.exception.SystemException"

              path="/common/exception.jsp"

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

              </exception>

             </global-exceptions>

            上面的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

             <html:errors/>

  • 相关阅读:
    MySQL存储引擎--MyISAM与InnoDB区别
    HTTP Keep-Alive模式
    php通过curl下载远程图片实例
    使用PHP QR Code生成二维码
    PHP中输出文件,怎么区别什么时候该用readfile() , fread(), file_get_contents(), fgets()
    SSDB 一个高性能的支持丰富数据结构的 NoSQL 数据库, 用于替代 Redis.
    html头文件设置常用之<meta>设置缓存
    redis使用watch完成秒杀抢购功能
    Linux信号(signal) 机制分析
    php信号处理
  • 原文地址:https://www.cnblogs.com/ymf123/p/4993022.html
Copyright © 2020-2023  润新知