struts 2 이상 처리

출처: http://blog.sina.com.cn/s/blog_4b62e4a901008jlo.html Struts 2 의 이상 처리 메커니즘:
모든 성숙 한 MVC 프레임 워 크 는 성취 의 이상 처리 체 제 를 제공 해 야 한다.Strut 2 도 예 외 는 아니다.Struts 2 는 성명 식 이상 처리 방식 을 제공 합 니 다.Struts 2 도 설 정 된 차단 기 를 통 해 이상 처리 메커니즘 을 실현 한다.
Struts 2 의 이상 처리 체 제 는 struts. xml 파일 에 < exception - mapping... > 요 소 를 설정 할 때 두 가지 속성 을 지정 해 야 합 니 다.
exception: 이 속성 은 이 이상 맵 이 설정 한 이상 형식 을 지정 합 니 다.
result: 이 속성 은 Action 에 이 이상 이 발생 했 을 때 시스템 이 result 속성 이 가리 키 는 결과 로 전 환 됩 니 다.
이상 맵 도 두 가지 로 나 뉜 다.
부분 이상 맵: < exception - mapping. > 요 소 는 < action. > 요소 의 하위 요소 로 설정 합 니 다.
전역 이상 맵: < exception - mapping... > 요 소 는 < global - exception - mappings > 요소 의 하위 요소 로 설정 합 니 다.
package com.dingxun.exception;   
  
import java.sql.SQLException;   
import com.opensymphony.xwork2.ActionSupport;   
  
public class Struts2Exception extends ActionSupport{   
       
    private static final long serialVersionUID = -87324321702425020L;   
    private String username;   
       
    public String getUsername() {   
        return username;   
    }   
  
    public void setUsername(String username) {   
        this.username = username;   
    }   
  
       
    public String execute() throws Exception{   
//      if("logo".equals(getUsername())){   
//          return SUCCESS;   
//      }else{   
//          throw new SQLException("      ");      trycatch  ,            ok 。
//      }   
        throw  new java.lang.Exception("    ");   
    }   
  
}  

 
 
<?xml version="1.0" encoding="UTF-8" ?>   
<!DOCTYPE struts PUBLIC   
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd">   
  
<struts>   
    <package name="aa" extends="struts-default">   
        <global-exception-mappings>   
        <exception-mapping result="all" exception="java.lang.Exception"></exception-mapping>   
        </global-exception-mappings>   
        <action name="execptionTest" class="com.dingxun.exception.Struts2Exception">   
            <result name="success">/exception/result.jsp</result>   
            <exception-mapping result="sql" exception="java.sql.SQLException"/>   
            <exception-mapping result="null" exception="java.lang.NullPointerException"/>   
            <result name="sql">/exception/sql.jsp</result>   
            <result name="null">/exception/null.jsp</result>   
            <result name="all">/exception/all.jsp</result>   
        </action>   
    </package>   
</struts>  

 
 위 는 사용자 가 로그 인 한 action 및 설정 입 니 다. 두 부분 이상 과 전체 이상 을 정의 합 니 다. 입력 한 사용자 이름과 비밀 번 호 는 callan 과 fjf 가 아 닐 때 SQLException 이상 을 던 지고 부분 이상 설정 이 작용 하 며 sql. jsp 로 방향 을 정 합 니 다. 부분 sql 이상 을 설명 하면 전체 이상 이 작용 하여 all. jsp 로 방향 을 정 합 니 다.
 
Struts 2 탭 을 사용 하여 이상 정 보 를 출력 할 수 있 습 니 다 < s: property value = "exception. message" / > < s: property value = "exception Stack" / >
sql. jsp 페이지
     사용자 이름 암 호 를 출력 할 수 있 습 니 다.
 
본 고 는 CSDN 블 로그 에서 왔 습 니 다. 전재 할 때 출처 를 표시 해 주 십시오. http://blog.csdn.net/thunder_1985/archive/2009/09/14/4550618.aspx
 
 
 
 
   출력 이상 정보:
Struts 2 탭 을 사용 하여 이상 한 정 보 를 출력 합 니 다:
< s: property value = "exception. message" / >: 출력 이상 대상 자체.
< s: property value = "exception Stack" / >: 이상 스 택 정 보 를 출력 합 니 다.
 
 
 
struts 2 의 이상 처리 체제 와 차단기 체 제 를 이용 하여 이상 처리 기능 을 편리 하 게 실현 할 수 있 습 니 다. Action 에서 이상 을 포착 하고 관련 된 이상 을 던 질 필요 가 없습니다. 이것 은 모두 차단기 에 맡 겨 서 해 드 립 니 다.
 
 
1. struts. xml 파일 에서 전역 이상 맵 을 설명 하고 해당 하 는 전역 이상 전송 은 다음 과 같 습 니 다.
﹤global-results﹥
﹤result name="error"﹥/admin/error/ErrDisplay.ftl﹤/result﹥
﹤/global-results﹥
﹤global-exception-mappings﹥
﹤exception-mapping result="error" exception="com.orizone.hbmobile.hbcm.struts.BusinessException"﹥﹤/exception-mapping﹥
﹤/global-exception-mappings﹥
 
businessException 은 이상 처리 클래스 입 니 다. 코드 는 다음 과 같 습 니 다.
 
public class BusinessException extends RuntimeException
{
 
    private static final long serialVersionUID = 0xc1a865c45ffdc5f9L;
  
    public BusinessException(String frdMessage)
    {
        super(createFriendlyErrMsg(frdMessage));
    
    }
 
    public BusinessException(Throwable throwable)
    {
        super(throwable);
    }
 
    public BusinessException(Throwable throwable, String frdMessage)
    {
        super(throwable);
     
    }
  
  
private static String createFriendlyErrMsg(String msgBody){
String prefixStr = "죄송합니다.";
String suffixstr = "잠시 후에 다시 시도 하거나 관리자 에 게 연락 하 십시오!";
 
StringBuffer friendlyErrMsg = new StringBuffer("");
 
friendlyErrMsg.append(prefixStr);
friendlyErrMsg.append(msgBody);
friendlyErrMsg.append(suffixStr);
 
return friendlyErrMsg.toString();
}
}
 
 
2. / admin / error / ErrDisplay. ftl 페이지
이 페이지 는 매우 간단 하 다.
﹤body﹥
﹤h2﹥
         이상 이 생 겼 어 요.
﹤/h2﹥
﹤hr/﹥
   ﹤h3 style="color:red"﹥
   <! - 이상 대상 획득 - >
  
    ${exception.message?default("")}
    ﹤/h3﹥
    ﹤br/﹥
    <! - 이상 스 택 정보 (개발 자 용) - >
    ﹤div style="display:none;"﹥
       ${exceptionStack?default("")}
    ﹤/div﹥
﹤/body﹥
﹤body﹥
﹤h2﹥
         이상 이 생 겼 어 요.
﹤/h2﹥
﹤hr/﹥
   ﹤h3 style="color:red"﹥
   <! - 이상 대상 획득 - >
  
    ${exception.message?default("")}
    ﹤/h3﹥
    ﹤br/﹥
    <! - 이상 스 택 정보 (개발 자 용) - >
    ﹤div style="display:none;"﹥
       ${exceptionStack?default("")}
    ﹤/div﹥
﹤/body﹥
 
3. 차단기 에서 흔히 볼 수 있 는 이상 을 포착 하고 우호 적 인 이상 정보 로 던 집 니 다. 관련 코드 는 다음 과 같 습 니 다.
public String intercept(ActionInvocation invocation) throws Exception
{
before(invocation);
String result = "";
 
try{
result = invocation.invoke();
}catch(DataAccessException ex){
throw new Business Exception ("데이터베이스 작업 실패!");
}catch(NullPointerException ex){
throw new Business Exception ("초기 화 되 지 않 은 대상 이나 존재 하지 않 는 대상 을 호출 했 습 니 다!");
}catch(IOException ex){
new BusinessException ("IO 이상!");
}catch(ClassNotFoundException ex){
throw new businessException ("지정 한 클래스 는 존재 하지 않 습 니 다!");
}catch(ArithmeticException ex){
throw new BusinessException ("수학 연산 이상!");
}catch(ArrayIndexOutOfBoundsException ex){
throw new Business Exception ("배열 아래 표 시 된 경 계 를 넘 습 니 다!");
}catch(IllegalArgumentException ex){
throw new Business Exception ("방법의 매개 변수 오류!");
}catch(ClassCastException ex){
throw new Business Exception ("유형 강제 변환 오류!");
}catch(SecurityException ex){
throw new Business Exception ("안전 원칙 위반 이상!");
}catch(SQLException ex){
throw new Business Exception ("데이터베이스 이상 조작!");
}catch(NoSuchMethodError ex){
throw new Business Exception ("방법 끝 에 이상 을 찾 았 습 니 다!");
}catch(InternalError ex){
throw new Business Exception ("Java 가상 컴퓨터 에 내부 오류 가 발생 했 습 니 다");
}catch(Exception ex){
throw new Business Exception ("프로그램 내부 오류, 작업 실패!");
}
 
after(invocation, result);
return result;
}
struts 2 이상 처 리 는 비교적 편리 하 다.

좋은 웹페이지 즐겨찾기