Action 클래스는 사용자의 요청과 비즈니스 로직을 처리하는 자바 클래스를 연결해 주는 역할을 하는데 Struts2에서는 Servlet을
사용하지 않고 일반 자바 클래스(POJO, Plain Old Java Object)로 액션을 구성할 수 있도록 하여 테스트가 쉬워졌으며
프레임워크와 결합도가 낮아 졌다.
<?xml:namespace prefix = o ns =
"urn:schemas-microsoft-com:office:office" />
Struts2에서 Action을 구성하는
세가지 방법
-클래스를 상속받지 않고 인터페이스를 구현하지 않은 일반 자바 클래스(POJO)
-com.opensymphony.xwork2.Action 인터페이스를 구현한 클래스
-com.opensymphony.xwork2.ActionSupport 클래스를 상속한 클래스
Action 클래스는 execute() 메소드를 구현하면 되는데 execute만이 메소드 명이 될 수 있는 것은 아니다.
Struts.xml에서 action의 method 속성에서 설정 함으로써 원하는 메소드명으로 변경이 가능하다.
1. POJO 클래스 이용
아래와 같이 POJO를 이용하여 Action 클래스를 만들면 어떤
API, Framework에 의존적이지 않은 액션을 만들 수 있지만 스트럿츠2 프레임워크의 기능을 최대한 활용하기 위해서는Action
인터페이스를 구현하거나 ActionSupport를 상속 받는 편이 좋다.
- 다음과 같은 일반 자바로 액션
클래스를 만들자. (hello1.action package에 만든다)
[HelloWorld.java]
package hello1.action;
public class
HelloWorld {
private String name;
private
String msg;
public String getMsg() {
return msg;
}
public
void setName(String name) {
this.name = name;
}
public String execute()
throws Exception {
msg = "Hello," + name;
return "success";
}
}
- Context 아래에 hello1 이라는 폴더 만들고
hello.jsp, result.jsp를 만들자.
[hello.jsp]
<form action=/struts2_helloworld/hello1/hello.action>
Input Your Name : <input type=text name=name>
<input
type=submit>
</form>
[result.jsp]
<h2>${msg}<h2>
- 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="hello1" namespace="/hello1"
extends="struts-default">
<action name="hello"
class="hello1.action.HelloWorld">
<result
name="success">/hello1/result.jsp</result>
</action>
</package>
</struts>
- 결과확인
http://localhost:8080/struts2_helloworld/hello1/hello.jsp 라고 입력한 후 확인하자.
<?xml:namespace prefix = v ns =
"urn:schemas-microsoft-com:vml" />
댓글 없음:
댓글 쓰기