struts2를 이용한 간단한 데이터 전송
데이터 전송방법 1
① Action
○ DTO + method
- dto랑 메소드를 같이 생성하여 관리
○ ActionSupprot를 상속받아 사용
○ 내장 변수
- SUCCESS : "success"
- INPUT : "input"
package com.test;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String userId;
private String userName;
private String message;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String execute() throws Exception {
message = userName + "님 방가방가..";
//실행이 잘 됬을 때 사용(SUCCESS = "success")
return SUCCESS;
}
}
② struts-test.xml
○ 패키지 설명
- 이름 : test ( 이름은 다름 패키지와 중복 되면 안된다)
- namespace="/itWill" : 주소에 /itWill이 왔을 때 이 패키지를 사용
- namespace안에는 공백이 들어가 있으면 안된다
<?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="test" extends="struts-default" namespace="/itwill" >
<!-- write.action이 오면 write.jsp로 이동 -->
<action name="write">
<result>/test/write.jsp</result>
</action>
<!-- TestAction을 가지고 이동 -->
<action name="write_ok" class="com.test.TestAction">
<!-- 가지고 온 값이 success이면 다음 실행 -->
<result name="success">/test/write_ok.jsp</result>
</action>
</package>
</struts>
③ 새로운 프로젝트를 생성하면 항상 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="default" extends="struts-default" namespace="" >
<global-results>
<result name="error">/exception/error.jsp</result>
</global-results>
</package>
<include file="struts-test.xml"></include>
</struts>
④ write.jsp
○ action에서 확장자면이 .action인 이유
- 처음에 환경설정을 할 때 struts.properties에서 지정했기 때문
- struts.action.extension=action
- 따로 지정을 안 해주면 기본값이 'action'이다
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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%>/itwill/write_ok.action" method="post">
아이디 :<input type="text" name="userId"><br/>
이름 :<input type="text" name="userName"><br/>
<input type="submit" value="보내기">
</form>
</body>
</html>
⑤ write_ok.jsp
○ struts-test.xml에서 write_ok.action이 오면 Action값을 가지고 이동하기 때문에 ${ }에서 Action의 변수를 사용할 수 있다
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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>
아이디:${userId }<br/>
이름:${userName }<br/>
메세지:${message }<br/>
</body>
</html>
데이터 전송방법 2
① User.java(DTO)
package com.test1;
public class User {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
② Action
○ Stuts2에서는 DTO를 action에 생성하여 사용하는데 DTO를 User.java파일에 별도로 생성(Domain Object)하였기 때문에 action에서는 DTO 객체를 생성한 후 사용하여야 한다.
package com.test1;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private User user;
//message는 DTO에서 사용하는 변수가 아님
private String message;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//message는 값을 넣어주기만 하므로 getter만 필요
public String getMessage() {
return message;
}
@Override
public String execute() throws Exception {
message = user.getUserName() + "님 방가방가...";
return "ok";
}
}
③ struts-test.xml
○ 위 프로젝트와 같은 struts-text.xml을 사용하므로 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="test" extends="struts-default" namespace="/itwill" >
<action name="write">
<result>/test/write.jsp</result>
</action>
<action name="write_ok" class="com.test.TestAction">
<!-- 가지고 온 값이 success이면 다음 실행 -->
<result name="success">/test/write_ok.jsp</result>
</action>
<action name="created">
<result>/test1/created.jsp</result>
</action>
<action name="created_ok" class="com.test1.TestAction">
<result name="ok">/test1/result.jsp</result>
</action>
</package>
</struts>
④ created.jsp
○ user.변수명
- action에서 DTO(User.java)의 객체를 user로 생성
- action의 객체에 직접 데이터를 집어 넣기때문에 변수명 앞에 user.붙여준다.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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%>/itwill/created_ok.action" method="post">
아이디 :<input type="text" name="user.userId"><br/>
이름 :<input type="text" name="user.userName"><br/>
<input type="submit" value="보내기">
</form>
</body>
</html>
⑤ result.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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>
아이디:${user.userId }<br/>
이름:${user.userName }<br/>
메세지:${message }<br/>
</body>
</html>
데이터 전송방법 3
① User.java(DTO)
package com.test2;
//Domain Object
public class User {
private String userId;
private String userName;
private String userPwd;
//mode값에 따라 입력창인지 출력창인지 구분
private String mode;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
}
② Action
○ Action 사용 방법
- 서블릿 : if문
- Struts1 : if문 → 메소드
- Struts2 : 메소드
○ Struts2의 기본 Action
- DTO(User.java)는 객체를 사용하기만 하므로 getter만 필요하다
- ModelDriven : Model은 데이터
< >안에는 사용하는 DTO를 작성
- prepare메소드 : 객체를 미리 생성
- getModel메소드 : dto를 관리 / 알아서 dto를 넘겨준다
package com.test2;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
/* Model은 데이터
* ModelDriven<User>
* < >안에는 사용하는 DTO를 작성
*/
public class TestAction extends ActionSupport implements Preparable,ModelDriven<User> {
private static final long serialVersionUID = 1L;
private User dto;
public User getDto() {
return dto;
}
//ModelDriven
@Override
public User getModel() {
return dto;
}
//Preparable
@Override
public void prepare() throws Exception {
//객체 생성
dto = new User();
}
}
○ TestAction.java
- Struts2에서는 기본적으로 메소드에 제공하는 매개변수가 없어 필요할 때마다 요청해서 사용해야 한다.
package com.test2;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public class TestAction extends ActionSupport implements Preparable,ModelDriven<User> {
private static final long serialVersionUID = 1L;
private User dto;
//원래는 DTO를 넘겨줘야 하나, Struts2에서는 getDTO()가 알아서 넘긴다. → request.setAttribute("dto",dto); 필요 X
public User getDto() {
return dto;
}
//ModelDriven
@Override
public User getModel() {
return dto;
}
//Preparable
@Override
public void prepare() throws Exception {
//객체 생성
dto = new User();
}
public String created() throws Exception {
/* write.action이 들어가면 다 created메소드를 찾아간다.
* 입력창에서는 mode값이 save로 넘어가 return값이 success가 되고
* 입력창으로 갈때는 mode이 null이어서 return값이 input이 된다. */
//get.Mode()는 항상 이중으로 검사, 반드시 null 후에 equals("")
if(dto==null || dto.getMode()==null || dto.getMode().equals("")){
return INPUT; //INPUT="input"
}
//request 요청
//context : 전체 (??)
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("message", "스트럿츠2..");
//setAttribute 데이터를 가지고 SUCCESS로 이동
return SUCCESS;
}
}
③ struts-test.xm
○ 위 프로젝트와 같은 struts-text.xml을 사용하므로 struts.xml에 추가 할 필요가 없다
○ 하나의 struts-text.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="test" extends="struts-default" namespace="/itwill" >
<action name="write">
<result>/test/write.jsp</result>
</action>
<action name="write_ok" class="com.test.TestAction">
<result name="success">/test/write_ok.jsp</result>
</action>
<action name="created">
<result>/test1/created.jsp</result>
</action>
<action name="created_ok" class="com.test1.TestAction">
<result name="ok">/test1/result.jsp</result>
</action>
</package>
<package name="test2" extends="struts-default" namespace="/modelDri" >
<!-- write.action이 들어가면 com.test2.TestAction을 찾아감 / 메소드는 created를 찾아감 -->
<action name="write" class="com.test2.TestAction" method="created">
<result name="input">/test2/write.jsp</result>
<result name="success">/test2/view.jsp</result>
</action>
</package>
</struts>
④ write.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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%>/modelDri/write.action" method="post">
아이디 :<input type="text" name="userId"><br/>
패스워드 : <input type="text" name="userPwd"><br/>
이름 :<input type="text" name="userName"><br/>
<input type="hidden" name="mode" value="save">
<input type="submit" value="보내기">
</form>
</body>
</html>
⑤ view.jsp
○ message는 dto에 생성한 값이 아니므로 그냥 작성
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
request.setCharacterEncoding("UTF-8");
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>
아이디:${dto.userId }<br/>
패스워드:${dto.userPwd }<br/>
이름:${dto.userName }<br/>
메시지:${message }<br/>
</body>
</html>
실행화면
○ 다음 화면은 1번 방법을 실행한 것
○ 모든 방법의 실행화면은 똑같다. 다만, 3번 방법에서는 패스워드가 추가된다