struts 2 - Interceptor

Published on: 2009. 7. 6. 17:35 by louis.dev


위의 그림은 Interceptor의 로직 그림이다
Interceptor는 4가지로 구분되며 각각 하는일은 다음과 같아

- preparable : 사용자로부터 전달된 데이터가 이곳을 통해 들어와 여기서 bean 객체에 담겨 stack에 쌓이게 된다.
- stack : stack의 환경에 맞춰 들어오는 데이터를 처리한다.
- Action : stack 의 결과로 execute method를 수행한다.
- ModelDriven : 결과를 result로 전달하는 역할을 한다.
   getModel() result로 보내질 객체를 생성한다. getModel로 vo를 보낸다 하면 jsp 페이지 에서 &{vo.name} 이런식으로 데이터를 받는게 아니라
다음과 같이 &{name} property이름만 해주면 된다.(actionsupport 를 사용하면 &{vo.name} 으로 해야 한다)

위 4가지 단계중 preparable, action,modeldriven은 Interface형태로 제공되기 때문에 implements해서 사용한다.

일반적으로 struts 2를 구현할때 ActionSupport Class를 상속받아 사용한다 이렇게 되면 위의 3가지를 사용자가 구현할 필요가 없지만 ActionSupport를 상속 받지 않으면 다음과 같은 interface를 구현하고 execute() method를 override 해야 한다.

action mapping을 수행하고 있는 xml 파일에서 package를 설정하는 부분이 있는데 이부분이

extends="struts-default"

이렇게 선언되어 있다면 기존에 구현된 interception을 수행하는 것이다.


<Intercepter의 종류>


공통적 사항
Preparable, Action, ModelDriven을 구현한 class 생성

------------------------------------------------------------------------------------------------------------
package person.actions;

import person.model.PersonVO;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;


@SuppressWarnings("unchecked")
public class WriteAction implements Action,
                                                    Preparable,
                                                   ModelDriven{
 private PersonVO vo;

 @Override
 public String execute()throws Exception {
  return SUCCESS;
 }
 //홈 요청이 들어오면 파라미터의 값을 받기 위해 객체를 생성하고
 //각 파라미터의 값을 프로퍼티에 저장한다.

 @Override
 public void prepare() {
  vo = new PersonVO();
    }
 //execute 메소드를 수행하고 결과를 Result로 전달하는 부분
 @Override
    public Object getModel() {
  return vo;
    }
}
------------------------------------------------------------------------------------------------------------
기본적인 class의 틀은 다음과 같다.
 - Preparable Interface의 prepare method를 구현한다.
 
public void prepare() {
  vo = new PersonVO();
    }

다음과 같은 틀로서 jsp페이지에서 들어온 데이터가 상단 property로 정의한 vo에 객체를 생성하고 초기화 하며 자동 맵핑되어 데이터가 들어가게 된다.

 - Action Interface의 execute method의 Business Logic을 구현한다.

 - 마지막으로 result로 데이터를 보내주기 위한 ModelDriven 의 getModel method를 통해 result로 데이터를 전달해 준다.
result를 통해 jsp페이지에서는 데이터를 EL테그를 사용한 ${vo.property name} 으로 접근하지 않고 ${Property name} 으로 접근할 수 있게 한다.


1) checkbox : jsp페이지의 체크박스에서 체크한 것만 데이터가 들어오게 된다.

① checkbox.xml 에서 action을 선언해 주고 intercepter-ref를 선언해 준다.

------------------------------------------------------------------------------------------------------------
<?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="interCheckbox" namespace="/checkbox" extends="struts-default">
      <action name="index"
              class="person.actions.IndexAction">
        <result>/person/write.jsp</result>
      </action>
      <action name="write"
              class="person.actions.WriteAction">
         <!-- struts2에서 지원하는 interceptor이름 -->
         <interceptor-ref name="checkbox">
         <!-- uncheckedValue는 예약어 :체크되지 않은 데이터는 오지 않는다.-->
          <param name="uncheckedValue">false</param>
         </interceptor-ref>
         <!-- 아래 세개는  default 이다-->
         <!-- Intercepter를 구현한 intercepor의 이름을 적어준다. -->

         <interceptor-ref name="prepare"/>
         <interceptor-ref name="modelDriven"/>
         <interceptor-ref name="params"/>
         <result>/person/result.jsp</result>
        
        
      </action>
   </package>
</struts>
------------------------------------------------------------------------------------------------------------

2) exception
exception Interceptor에는 2가지 방식이 있다.
 ① global Interceptor exception
     - 어디에서 일어나는지 모르는 exception이 발생할때

package 바로 아래 action 보다 위에 설정한다.

<global-results>
      <result name="exception">/exception/exception.jsp</result>
</global-results>
     
<global-exception-mappings>
      <!-- result에 정의되어있는 위쪽의 globla-results의 name이랑 똑같은데 찾아 들어간다. -->
      <exception-mapping result="exception" exception="java.lang.Exception"/>
</global-exception-mappings>



 ② local Interceptor exception
     - 어떠한 action에서 발생하는 에러를 처리할때
        <action>태그 사이에 기술한다.

<action name="register"
           class="com.myhome.upload.actions.UploadMultiAction"
           method="register">
      <!-- 특정액션에서 예외가 발생할 때 인터셉터를 적용한다. -->
      <exception-mapping result="exception" exception="java.lang.NullPointerException"/> 
      
      <result name="success" type="dispatcher">/WEB-INF/upload/result.jsp</result>
      <result name="error" type="dispatcher">/WEB-INF/upload/fail.jsp</result>
      <result name="exception">/exception/exception.jsp</result>
     </action>

다음과 같이 선언한 UploadMultiAction class의 register method 에서 NullPointerException이 발생할 경우 exception 이라는 result name으로 데이터가 반환된다.

에러 메시지는 ExceptionStack 라는 곳에 쌓이게 되며 jsp page 에서 ${exceptionStack} 라는 EL태그로 에러의 LOG 내용을 확인 할 수 있다.
또 struts 2 태그인 <s:actionerror/>,<s:actionmessage/>,<s:fielderror/> 들로도 Exception message를 출력할 수 있다.

Exception Message의 추가는 Actionclass의
this.addActionMessage(bean.getName() + "님이 파일 오류를 발생하였음.");
throw new NullPointerException("파일을 올려주세요");

다음과 같이 에러메시지를 추가 할 수있다.

3) parameters Interceptor

사용자로 부터 전달되는 어떠한 파라미터를 선택적으로 제어 하거나 모두 받지 않을 수 있다.

- ParameterNameAware interface : 선택적으로 파라미터를 받지 않을 수 있다.
ParameterNameAware Interface를 implements 하고 acceptableParameterName method를 구현한다.

acceptableParameterName method

public boolean acceptableParameterName(String parameterName) {       // 파마리터 이름이 name인 것을 받지 않겠다.
  if("name".equals(parameterName)){
   return false;
  }
  return true;
 }

- NoParameters Interface
  다음의 Interface를 implements 하는 것만으로 전달되는 파라미터 들을 막을 수 있다


4) Static Parameters Interceptor
jsp 페이지에서 전달되는 파라미터 값 말고 xml파일에서 데이터를 넘겨줄 수 있다.

xml 의 action 안에 다음과 같이 설정한다.

<param name="name">홍길동</param>     
<interceptor-ref name="staticParams"/>


action class에서 param name 으로 getter와 setter를 생성해 준다.

5) time Interceptor
action 이 실행 되는 시간을 구한다.
action 태그 내에

<interceptor-ref name="timer"/>

다음과 같이 설정하면 된다.









'Framework > STRUTS 2' 카테고리의 다른 글

struts 2 - JFree Chart plugin  (0) 2009.07.08
struts 2 - Tiles Plug in  (6) 2009.07.08
struts 2 - properties 파일  (1) 2009.07.05
struts 2 - upload & download  (0) 2009.07.05
struts 2 - session 사용하기  (1) 2009.07.05