본문 바로가기
IT_Developers/struts2

Struct2 - Preparable 이란? 사용법 / 기본 예제

by 고코더 2019. 10. 23.

prepare() 기본 사용법


안녕하세요.
고코더 입니다.


com.opensymphony.xwork2.Preparable 속한 prepare 인터페이스는 Action의 prepare() 메소드를 실행 합니다.
이 인터셉터는 Client로 부터 전달된 모든 데이터를 가로채는 역할을 합니다. 그렇기에 
Action이 실행되기전에 특정 메소드를 실행 시킬 수 있습니다. 



implements 구현

 1. 사용법은 implements 속성으로 구현해야 합니다.
기존에 저희가 만든 TestAction에 Preparable를 구현합니다. 

1
public class TestAction extends ActionSupport implements  Preparable {
cs


 2. 그럼 아래와 같은 오류가 발생 합니다. 인터페이스를 구현했으니 prepare()를 오버라이드 해야 합니다.


 3. 아래 소스처럼 prepare()를 오버라이드 해줍니다. 이렇게 하면 이 액션이 호출될때 가장 먼저 실행되게 됩니다. 

1
2
3
4
@Override
public void prepare() throws Exception {
  
}
cs


예제 소스 수정 / TestAction



 4. 이제 지금까지 만들어온 예제에 해당 코드들을 삽입하였습니다. 
String Content에 변수를 미리 선언합니다.
하지만 해당 변수는 getContent()을 통해 파라미터 변수를 입력 받습니다.
만약 prepare가 액션보다 먼저 호출된다면 Pretxt안에 "미리 선언한 내용"이 입력될 것입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package test;
 
import java.sql.SQLException;
 
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
 
public class TestAction extends ActionSupport implements Preparable {
 
    String Title;
    String Content = "미리 선언한 내용";
    String Pretxt;
 
    // Preparable 인터페이스 가장 먼저 실행 된다.
    @Override
    public void prepare() throws Exception {
        // CONTENT 변수안에 있는 텍스트가 SET 담기기전에 가져온다.
        this.Pretxt = this.Content;
    }
 
    public String getTitle() {
        return Title;
    }
 
    public void setTitle(String Title) {
        this.Title = Title;
    }
 
    public String getPretxt() {
        return Pretxt;
    }
 
    public void setPretxt(String pretxt) {
        Pretxt = pretxt;
    }
 
    public String getContent() {
        return Content;
    }
 
    public void setContent(String Content) {
        this.Content = Content;
    }
 
    public String getView() {
        // this.Title = "제목";
        // this.Content = "내용";
        return SUCCESS;
    }
 
    /* 데이터베이스 연결 테스트를 위한 */
 
    TestDao dao = new TestDao();
    String ConYN;
 
    public String getConYN() {
        return ConYN;
    }
 
    public String conTest() throws SQLException {
        this.ConYN = dao.conTest();
        return SUCCESS;
    }
 
}
cs



결과 화면



 5. 결과화면을 보겠습니다. 파라미터에 담긴 제목과 내용이 출력되고 prepare에는 contet초기 변수를 담아둔 "미리 선언한 내용"
이라는 글자가 나타납니다. 이는 액션에서 가장 먼저 동작했기에 Content에 담긴 내용이 사라지기전에 변수에 담아 표현 할 수 있었습니다.
http://localhost:8080/Struts2Gocoder/test/view.action?Title=%EA%B3%A0%EC%BD%94%EB%8D%94&Content=%EB%B8%94%EB%A1%9C%EA%B7%B8


 6. 다시 한번 설명 드리면 prepare()는 인터페이스은 Preparable을 오버라이드 되어 실행됩니다. 이 기능을 테스트 하기 위해 Content에 초기 선언한 변수를 Pretxt로 먼저 가져올 수 있는지 테스트 하였습니다.




마무리


참 쉽죠?


댓글