본문 바로가기

Struts/Struts Programming

[Struts] 스트럿츠 흐름과 파라미터 값 전달하기

반응형

ActionSupport 클래스에 대한 이해

01) params 인터셉터

 ※ 인터셉터(interceptor)는 액션의 호출을 동적으로 가로채는 객체로서 다양한 기능을 제공한다.


 -. params 인터셉터는 요청 파라미터와 동일한 이름을 가진 액션의 프로퍼티에 값을 저장하는 역할을 한다.

 struts.xml의 일부

<struts>
    <package name = "ch04" extends = "struts-default">
        <action name = "HelloWorld02" class = "action.HelloWorld02">
            <interceptor-ref name = "params"/>
            <result name = "success">/helloWorld.jsp</result> …… ⓐ
        </action>
    </package>
</struts>


 -. <interceptor-ref /> 요소는 <interceptor /> 요소를 참조하겠다는 의미이다.

 -. "params"에 대한 <nterceptor /> 요소의 정의는 struts2-core-버전.jar 안에 포함되어 있는

    스트럿츠2가 제공하는 struts-default.xml 파일에 있다.

 struts2-core-2.3.4.1.jar → struts-default.xml

 -. struts-default.xml 파일은 strtus-default 패키지가 설정되어 있고, 해당 struts-default 패키지 내에는

    <interceptor /> 요소들이 포함되어 있다.

 -. "params"는 strtus-default 패키지 내에 108 줄에서 <interceptor /> 요소로 정의되어 있음을 확인할 수 있다.


 -. <include /> 요소를 설명할 때 struts.xml은 묵시적으로 struts-default.xml 파일이 in-clude된다고 설명하였다.

    그렇기 때문에 struts.xml의 <package /> 요소에서 extends 속성에 "struts-default"를 기술해서 struts-default.xml 파일의

    "struts-default" 패키지를 상속받을 수 있다.

 -. struts.xml의 <package />요소가 "struts-default" 패키지를 상속받기 때문에

    struts-default.xml 파일의 "struts-default" 패키지 내에 정의된 "params"에 대한 <interceptor /> 요소를

    struts.xml에서 <interceptor-ref /> 요소로 참조하여 사용할 수 있다.


■ 파라미터 값을 전달받는 예제의 동작 원리



 -. HelloWorld02.action을 요청하면 HelloWorld02 액션  객체가 인스턴스화되면서 params 인터셉터가 요청 시 전달되는

    파라미터(name)를 읽어 액션의 setter(setName)를 호출한다.


 -. setName( ) 메소드를 통해서 name 프로퍼티의 값이 'Devil'로 세팅된 후에 execute( ) 메소드가호출된다.


 -. execute() 메소드에서는 "Hello," 다음에 요청 파라미터 값(Devil)으로 세팅된 name프로퍼티 값을 연결한 후에 'return SUCCESS;' 하였다.

    때문에 'success' <result> 요소, params 인터셉터 소스창 ⓐ에 의해서 helloWorld.jsp가 실행 결과를 출력할 페이지가 되고

    helloWorld.jsp에서 표현 언어로 ${message}와 같이 출력을 하면 'Hello, Devil!'이 출력된다.


 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Chapter04</display-name>
 
  <!-- 스트럿츠2의 핵심 컨트롤러 역할을 수행하는 FilterDispatcher 클래스로 struts2란 필터를 등록한다. -->
  <filter>
    <filter-name>struts2</filter-name>
    <!-- 스트럿츠2의 핵심 컨트롤러 역할을 수행하는 클래스 -->
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    <init-param>
        <!-- 스트럿츠2에서 한글 처리 -->
        <param-name>struts.i18n.encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
  </filter>
 
  <!-- URL 확장자가 action일 때 FilterDispatcher 필터가 실행되도록 매핑한다. -->
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 struts.xml

<?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 = "ch04" extends = "struts-default">
        <action name = "HelloWorld02" class = "action.HelloWorld02">
            <interceptor-ref name = "params"/>
            <result name = "success">/helloWorld.jsp</result>
        </action>
    </package>
</struts>

 helloWorld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>결과를 위한 JSP 페이지</title>
</head>
<body>
<h1>
${message}
</h1>
</body>
</html>
 nameForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>입력 폼을 위한 JSP 페이지 작성하기</title>
</head>
<body>
<form action = "HelloWorld02.action" method = "post">
    <input type = "text" name = "name"/>
    <input type = "submit" value = "보내기"/>
</form>
</body>
</html>

 HelloWorld02.java

package action;

import com.opensymphony.xwork2.Action;

public class HelloWorld02 implements Action {
   
    // HelloWorld02 액션에서도 HelloWorld 액션에서와 마찬가지로
    // set / get 메소드를 갖는 필드를 추가할 수 있다.
    // 스트럿츠 2의 액션은 자바 빈의 규칙을 따르기 때문에 필드에 대한 직접 접근하지 못하도록
    // private 멤버로 지정하고, 이를 public 멤버로 선언된 메소드를 사용하도록 한다.
    private String message;
    private String name = "Angel";
   
    // message 필드는 getter만 존재하므로 이 값을 외부에서 사용하기만 하고 변경하지 못하는
    // read only 프로퍼티가 된다.
    public String getMessage() {

        return message;
    }
   
    // 반면 name 필드는 외부에서 사용하기만 하고 변경하지는 못하도록 하기 위해서 setter만 정의해 둔다.
    public void setName(String name) {
       
        this.name = name;
    }
   
    @Override
    public String execute() throws Exception {
       
        this.message = "Hello, " + name + "!";
       
        return SUCCESS;
    }
}

 출력화면



반응형