본문 바로가기

sturts2

struts2 ModelDriven

web.xml(<url-pattern>/*</url-pattern> 때문에 클라이언트의 모든 요청은 struts2를 기반으로 작동하게 된다)


<?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>struts</display-name>

  <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>

  

    <!-- 스트러츠 환경 정의 시작 -->

<filter>

    <filter-name>struts2</filter-name>

    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>struts2</filter-name>

    <url-pattern>/*</url-pattern>

</filter-mapping>

    <!-- 스트러츠 환경 정의 끝 -->

</web-app>


=================================================================================================================================================


struts.xml(여럿이 작업할 때 유지보수를 효율적으로 하기 위해서 이곳이 아닌 다른곳에서 struts.xml 작업을 하고 이곳에서는 include로 내용을 가져오기만 한다. 이번 예제 에서는 struts-test.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>

   <!-- Configuration for the default package. -->

    <package name="default" extends="struts-default" namespace="" >        

        <global-results>

            <result name="error">/exception/error.jsp</result>

        </global-results>

   </package>

   

   <include file="struts-test.xml"/>


</struts>


=================================================================================================================================================


struts-test.xml(이번예제의 실제 struts2를 처리하게 되는 파일)

<?xml  version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<package name="test" extends="struts-default" namespace="/test">
<action name="test">
<result>/test/test.jsp</result>
</action>
<action name="test_ok" class="com.test.TestAction">
<result name="ok">/test/test_ok.jsp</result>
</action>
</package>

<package name="user" extends="struts-default" namespace="/user">
<action name="write" class="com.user.UserAction" method="created"> 
     <result name="input">/user/write.jsp</result>
     <result name="success">/user/write_ok.jsp</result>
</action>
</package>

<package name="user1" extends="struts-default" namespace="/user1">
<action name="write" class="com.user1.UserAction" method="created">
    <result name="input">/user1/write.jsp</result>
    <result name="success">/user1/write_ok.jsp</result>
</action>
</package>
</struts>

설명 : 
test와 user는 이전 예제이니 무시해도됨.
주소창에 localhost:9090/user1/write.action을 친다면 namespace의 /user1을 통하여 해당 package안으로 진입한다.
그리고 주소창의 write.action이 action name의 write를 보고 해당 action으로 진입한다. 확장자가 action이 가능한것은 struts2의 디폴트 확장자가 action이기 때문이다
(struts.properties에 기본적인 설정을 할 수 있으며 확장자를 변경할 수 있다. 캐릭터 셋도 기본설정 가능하며 디폴트는 UTF-8 이다)
진입한 action의 UserAction class를 실행하게되고 그 안의 created를 메소드를 실행한다.
created 메소드의 처리 결과에 따른 return값을 받는데 
return값이 input이면 /user1/write.jsp로 forwarding하고
return값이 success이면 /user1/write_ok.jsp로 forwarding하게 된다.
result의 name을 명시하지 않으면 기본값으로 success가 셋팅된다.

이전 글의 예제인 test와 다른점은 action 태그를 2번 사용하지 않고 ActionClass의 처리결과따른 return값을 다르게 받아서 간결하게 처리하였다.   
   
=================================================================================================================================================


write.jsp


<%@ page  contentType="text/html; charset=UTF-8"%>

<%@page trimDirectiveWhitespaces="true"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%String cp = request.getContextPath();%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>


<form action="<%=cp %>/user/write.action" method="post">

이름 : <input type="text" name="user.name"/><br/>

나이 : <input type="text" name="user.age"/><br/>

전화번호 : <input type="text" name="user.tel"/><br/>

<input type="hidden" name="user.mode" value="zzz">

<input type="submit" value="전송하기"/><br/>

</form>


</body>

</html>


=================================================================================================================================================


UserAction.java


package com.user1;


import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;


/*

 * - modelDriven 방식을 이용한 클라이언트 파라미터 전달받기 

 * modelDriven인터셉터는 ModelDriven인터페이스를 구현한 액션클래스에서 getModel() 메소드를 

 *  실행하여 리턴받은 모델 오브젝트를 VisualStack의 최상단으로 올라감.

 * modelDriven인터셉터를 붙이고 params 인터셉터를 붙이면 모델 오브젝트의 파라미터로 셋팅(클라이언트의 파라미터를)

 *  prepare인터셉터는 Preparable 인터페이스의 prepare() 메소드를 호출하여 모델 인터페이스를 초기화 하기위해 사용

 * prepare인터셉터는 modelDriven 인터셉터위에 있어야함

 * 

 *

 * 1) prepare 인터셉터는 모델객체생성

 * 2) modelDriven인터셉터는 모델객체를 최상단으로 올림

 * 3) params 인터셉터는 최상단의 객체에(모델 객체) 클라이언트가 넘겨준 파라미터를 셋팅함

 * 

 * 따라서  modelDriven 방식은 setter가 없어도 됨

 */


public class UserAction extends ActionSupport implements Preparable, ModelDriven<User>{

private static final long serialVersionUID = 1L;

private User user;

public User getUser() {   // write_ok.jsp로 User.java에 있는 데이터를 보내줌. 

return user;    // setter가 없는 이유는 Prepare,ModelDriven,params 3개의 인터셉터 조합으로 클라이언트가 보낸 데이터를 User.java로 곧바로 데이터를 셋팅하는 것이 가능하기 때문이다. setter대신 3개의 인터셉터를 조합시켰다고 보면됨. 

}    // 이럴경우 이곳에서 보낸 데이터를 jsp에서 받을 때 도메인을 사용하지 않고 바로 사용가능한 이점이 있다.


public String created() throws Exception{

if(user==null || user.getMode()==null)

return INPUT;

user.setName(user.getName()+"님 방가방가");

return SUCCESS;

}


@Override

public User getModel() { // modelDriven 메소드=> 리턴받은 모델 오브젝트를 VisualStack의 최상단으로 올림

return user;

}


@Override

public void prepare() throws Exception { // preparable 메소드 => 모델 인터페이스를 초기화 하기위해 사용

user=new User();

}


}


// 모델드리븐 방식으로 인하여 프로퍼티 데이타의 출력을 바로 할 수 있다.

// 최상단으로 끌어올린다는 것은 도메인 따위를 사용하지 않고 바로 사용할 수 있다는 뜻이기 때문이다.  ${user.name}이 아닌 ${name}으로 바로 사용가능

// 모델드리븐 사용법

// 1. ActionSupport를 상속받고 Preparable과 ModelDriven을 implements하여 재정의 한다.

// 2. ModelDriven의 getModel()메소드는 변수를 리턴하여 재정의

// 3. Preparable의 prepare()메소드는 객체를 생성, 초기화하여 재정의

// 4. 프로퍼티를 입출력할 자바 클래스의 private를 만든다.

// 5. 해당 클래스의 getter만 만든다


=================================================================================================================================================

User.java


package com.user;


public class User {

private String name, tel;

private int age;

private String mode;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getMode() {

return mode;

}

public void setMode(String mode) {

this.mode = mode;

}

}


=================================================================================================================================================

write_ok.jsp


<%@ page  contentType="text/html; charset=UTF-8"%>

<%@page trimDirectiveWhitespaces="true"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%String cp = request.getContextPath();%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>


이름 : ${name }<br/> <!-- ${user.name} 과 같이 작성하지 않아도 된다. -->

나이 : ${age }<br/>

전화 : ${tel }


</body>

</html>


=================================================================================================================================================

=================================================================================================================================================


결과: localhost:9090/user/write.action을 주소창에 치고 이름과 나이,전화번호를 클라이언트에게 입력받아 submit으로 전송하면 


이름 : 홍길동

나이 : 17

전화 : 1234-1234


와 같이 출력된다.

'sturts2' 카테고리의 다른 글

struts2 도메인을 이용한 사용법  (0) 2013.07.21
struts 2 구조를 이해하는 예제  (0) 2013.07.21