struts2 对异常的处理

 

struts2 对异常的处理

使用自定义类处理异常
1.定义异常类
2.定义拦截器类,并加入默认拦截器栈
3.struts.xml 配置
4.注意,struts-default.xml 有默认的异常处理拦截器:name="exception", 默认拦截器栈:defaultStack


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

<include file="struts-default.xml"></include>

<package name="default" extends="struts-default">
        <interceptors>
            <interceptor name="exceptionInter" class="cn.demo.util.DefaultExceptionInterceptor"></interceptor>
            <interceptor-stack name="demoStack">
             <interceptor-ref name="defaultStack"></interceptor-ref>
             <interceptor-ref name="exceptionInter"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
       
        <!-- 异常处理后,能够提供友好的用户界面 -->
        <global-results>
   <result name="exceptionPage">/WEB-INF/pages/fail.jsp</result>
  </global-results>
  <global-exception-mappings>
   <exception-mapping  exception="java.lang.Exception" result="exceptionPage"/>
  </global-exception-mappings>
  
    </package>
   
    <package name="sys" extends="default" namespace="/sys">
  <!-- action使用spring的bean -->
        <action name="*_*" class="{2}" method="{1}">
         <interceptor-ref name="params" />
         <result name="userlist">/pages/user/list.jsp</result>
         <result name="useradd">/pages/user/add.jsp</result>
         <result name="userupdate">/pages/user/update.jsp</result>
         <result name="userlook">/pages/user/look.jsp</result>
         
         <interceptor-ref name="demoStack"></interceptor-ref>
        </action>
 </package>

</struts>

拦截器:
public class DefaultExceptionInterceptor extends AbstractInterceptor {
 
  protected Logger log = LoggerFactory.getLogger(this.getClass());
  //protected Logger myexLogger = LoggerFactory.getLogger("my-exception");
 public String intercept(ActionInvocation inv) throws Exception {
  String result = null;
  try{
   result = inv.invoke();
  }catch(DefaultException e){
    inv.getStack().push(new ExceptionHolder(e));
    result = "exceptionPage";
  }
  return result;
 }
}

自定义异常
public class DefaultException extends Exception{
 
 public DefaultException(String msg){
  super(msg);
 }
}


public class UserAction extends ActionSupport{
 
 private IUserService userService;
 private static final Logger log = Logger.getLogger(UserAction.class);
 
 
 public String list() throws DefaultException{
  try{
  
  }catch(Exception e){
   throw new DefaultException(e.getMessage());
  }
  return "success";
 }
}

 

 

你可能感兴趣的:(struts2)