본문 바로가기

Java

Struts 1 설치 및 간단한 실습

Struts 1.x 설치하기

2010.6.13일 기준 Struts 1.3.10을 http://struts.apache.org/ 로 이동하여 다운받는다.

Direct Download Link=> http://apache.naggo.co.kr/struts/binaries/struts-1.3.10-all.zip

 

..\struts-1.3.10\lib 에서 아래 5개의 jar 파일을 복사하여 해당 프로젝트의 WEB-INF/lib에 복사한 후, WEB-INF 폴더에 struts-config.xml 파일을 생성한다.

 

[ 실습1 ]

  • 기본설정

모든 Client의 요청은 ActionServlet이 받아서 처리하도록 Web.xml에서 아래와 같이 설정한다.

<servlet>

<servlet-name>struts</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup> //Comment1

</servlet>

<servlet-mapping>

<servlet-name>struts</servlet-name>

<url-pattern>*.do</url-pattern> //Comment2

</servlet-mapping>

Comment1 : //ActionServlet WebApplication 시작시 Load 있도록 설정.

Comment2 : *.do 끝나는 모든 요청에 대해서 ActionServlet 처리하도록 한다.

 

  1. 단순히 JSP Page로 Forwarding 하기!

Struts에서는 기본적으로 모든 JSP 페이지가 User에게 접근 허용되어서는 안되므로 단순 HTML이든, JSP 페이지 이던지 Controller를 거치도록 설정해야 한다.

struts-config.xml

<struts-config>

<action-mappings>

<action path="/welcome" forward="/src01_forward/welcome.html"/>

</action-mappings>

</struts-config>

<!-- Client에서 http://[ip][port No.]/application_name/welcome.do로

요청을 해오면 /src01_forward/welcome.html 으로 수행을 바로 넘긴다. -->

 

req.html

Welcome.html

<html>

<head>

<title>Insert title here</title>

</head>

<body>

<a href="../welcome.do">Go Welcome Page</a>

<!-- <a href="/struts_src/welcome.do">Go Welcome Page</a> -->

</body>

</html>

<html>

<head>

<title>Insert title here</title>

</head>

<body>

Welcome to your Visit~

</body>

</html>

위 그림과 같이 req.html을 실행하여 Link를 누르면 struts-config.xml에 의해 Action Servlet으로 수행이 먼저 넘어간 후, 설정된 Welcome.html으로 forward 된다.

  1. Action 사용하기.
  • ActionServlet Class 파일 작성하기

HelloAction.java

package struts.hello.action;

 

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

 

public class HelloAction extends Action{

 

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{

 

String hello="안녕";

request.setAttribute("hello", hello);

 

ActionForward forward=mapping.findForward("greeting");

//위와 아래 중 양자택일 가능

/*ActionForward forward=new ActionForward("/hello/hello.jsp",false);*/

return forward;

}

}

 

  • struts-config.xml에 위에서 생성한 action파일 등록하기.

struts-config.xml

<action path="/hello" type="struts.hello.action.HelloAction">

<forward name="greeting" path="/hello/hello.jsp" redirect="false"/>

</action>

<!-- Client에서 http://localhost:8088/struts_src/hello.do 으로

요청을 해오면 struts.hello.action.HelloAction.execute() 실행시키고

"greeting이란 이름의 Mapping 정보가 들어오면 정보를 /hello/hello.jsp

redirect="false" 옵션으로 인해 RequestDispatcher 방식으로 전송한다.-->

 

  • hello.jsp 파일 생성
     

    <%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

    <html>

    <head>

    <title>Hello.JSP</title>

    </head>

    <body>

    <!-- Print1 -->

    <% String hello=(String)request.getAttribute("hello"); %>

    <%= hello %><br/>

    <!-- Print2 -->

    ${hello }

    </body>

    </html>

  1. ActionForm 사용하기.

Struts는 Client가 요청시에 보낸 Form Data를 ActionForm 객체에 넣어 action의 execute( ) Method를 호출시에 넘겨준다.

 

ActionForm은 FormData를 저장할 property들과 이 property들을 초기화할 수 있는 reset() method와 이 Data들을 검사할 수 있는 validate() Method를 가질 수 있다. 또한 ActionForm 은 Value Object(=VO)와 유사하다 할 수 있다.)

 

여기에서는 사용자가 보내온 로그인 정보(ID & PW & ADMIN)를 ActionForm을 사용하여 처리해본다.

 

  • 우선 사용자가 보내온 Form Data를 저장할 클래스를 생성한다. 생성 요령은 VO 와 동일하게 Private로 Instance Member Variable을 만들고, 이들에 접속하기 위한 Public 타입의 Setter/Getter Method를 만든다. 부과적으로 reset() 및 validate()도 필요시 생성한다.

     

LoginForm.java

package struts.login.actionform;

 

//Import 정보 생략

public class LoginForm extends ActionForm{

private String id;

private String password;

private boolean admin;

 

//Form Data를 Setting 하기 전에 Attribute 초기화 작업을 처리

public void reset(ActionMapping mapping, HttpServletRequest request){

System.out.println("reset() 수행");

this.id=null;

this.password=null;

this.admin=false;

}

//Setter & Getter Method()

public String getId() {

System.out.println("setId() 호출"+id);

return id;

}

public void setId(String id) {

this.id = id;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public boolean isAdmin() {

return admin;

}

public void setAdmin(boolean admin) {

this.admin = admin;

}

 

@Override

//toString()

public String toString() {

return "LoginForm [id=" + id + ", password=" + password + ", admin="

+ admin + "]";

}

}

 

  • struts-config.xml에 <form-beans> 태그를 사용하여 위에서 생성한 LoginForm.java 파일을 등록하고, <action> 태그에서 참조하여 사용한다.

struts-config.xml

<form-beans>

<form-bean name="loginForm" type="struts.login.actionform.LoginForm">

</form-bean>

 

<action-mappings>

<action path="/login_form" type="struts.login.action.form.LoginFormAction" name="loginForm" scope="request">

<forward name="login_success" path="/src03_login_form/login_success.html" redirect="true"/>

<forward name="login_form" path="/src03_login_form/login_form.jsp" />

</action>

</action-mappings>

 

  • 사용자의 입력을 받을 login_form.jsp 생성

login_form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<html>

<head>

<title>Insert title here</title>

</head>

<body>

<font color="red" size="3" >${requestScope.message }</font>

<form action="/struts_src/login_form.do" method="post">

ID : <input type="text" name="id"/><br/>

PW : <input type="text" name="password"/><br/>

<input type="submit" value="Login"/>

</form>

</body>

</html>

 

  • 위 단계까지 jsp 파일에서 사용자가 입력한 Form Data를 받아 ActionForm 에 넣었고, 이제 Action을 수행할 LoginFormAction.java 파일을 생성한다.

LoginFormAction.java

package struts.login.action.form;

//Import 정보 생략

/**

* LoginFormAction->ActionForm을 이용해서 로그인 처리

* path=/login_form

*

* 성공시 : login_success.jsp

* 실패시 : login_form.jsp

* @author Administrator

*/

public class LoginFormAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) throws Exception{

 

ActionForward forward=null;

LoginForm login_Form=(LoginForm) form;

 

//Business Service Logic

LoginService service=new LoginService();

LoginVO lvo=service.getLoginInfo(login_Form.getId());

 

if(lvo!=null){//ID

if(lvo.checkPassword(login_Form.getPassword())){//true = Login Success

HttpSession session=request.getSession();

session.setAttribute("login_info", lvo);

 

forward=mapping.findForward("login_success");

}else{// Login Fail

request.setAttribute("message", "please, recheck your password");

}

}else {//ID

request.setAttribute("message", "please, recheck your ID");

}

 

if(forward==null){

forward=mapping.findForward("login_form");

}

return forward; //응답처리

}

}

 

LoginVO.java

package struts.login.vo;

 

public class LoginVO {

private String id;

private String password;

private boolean admin;

 

public LoginVO(String id, String password, boolean admin) {

super();

this.id = id;

this.password = password;

this.admin = admin;

}

 

public LoginVO() {

super();

}

 

public String getId() {

return id;

}

 

public void setId(String id) {

this.id = id;

}

 

public String getPassword() {

return password;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public boolean isAdmin() {

return admin;

}

 

public void setAdmin(boolean admin) {

this.admin = admin;

}

 

@Override

public String toString() {

return "LoginVO [admin=" + admin + ", id=" + id + ", password="

+ password + "]";

}

public boolean checkPassword(String password){

if(this.password.equals(password)){

return true;

}

return false;

}

}

 

  1. DynaActionForm 사용하기

위의 실습과 달리 ActionForm을 정적으로 생성하지 않고, 가상의 Form을 동적으로 생성하여 사용할 수 있다. 이는 내부적으로 map으로 Property를 관리하는 방식으로 ActionForm 클래수를 줄일 수 있는 장점이 있다.

 

실습으로 DynaActionForm을 이용한 사칙연산의 결과값을 구해본다.

  • 가장 우선 사용자로부터 피연산자 2개와 연산자를 받아올 JSP 페이지를 생성한다.

calc_form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<html>

<head>

<title>Insert title here</title>

</head>

<body>

<p>계산</p>

<form action="/struts_src/calc.do" method="post">

피연산자1 : <input type="text" name="operand1"/>

피연산자2 : <input type="text" name="operand2"/><br/>

연산자 선택 : <br/>

+<input type="radio" name="operator" value="+" checked/>,

-<input type="radio" name="operator" value="-" />,

*<input type="radio" name="operator" value="*" />,

/<input type="radio" name="operator" value="/" /><br/>

<input type="submit" value="Result"/></form>

 

</body>

</html>

 

  • struts-config.xml에서 위에서 Form Data를 넘겨받을 /calc에 대한 곳을 지정한다.

struts-config.xml

<form-bean name="calcForm" type="org.apache.struts.action.DynaActionForm">

<!-- DynaActionForm 가질 property 설정 (Map Key 설정됨) -->

<form-property name="operand1" type="java.lang.Integer"></form-property>

<form-property name="operand2" type="java.lang.Integer"></form-property>

<form-property name="calcResult" type="java.lang.Integer"></form-property>

<form-property name="operator" type="java.lang.Character"></form-property>

</form-bean>

 

 

<action-mappings>

<action path="/calc" type="struts.calc.action.CalcAction" name="calcForm" scope="request">

<forward name="result" path="/src04_dynaform/calc_result.jsp"/>

</action>

</action-mappings>

 

/calc로 요청이 왔을 때 struts.calc.action.CalcAction 클래스로 수행을 넘기는데, calcForm이란 이름의 Form-Bean 객체에 사용자로부터 넘겨받은 FormData 값들을 넣고, Request 영역에도 값들을 넣어둔다. 그리고 forward 객체의 이름이 "result" , 해당 경로로 수행을 넘긴다

 

  • 위에서 생성된 DynaActionForm 넘겨받아 BL 수행할 CalcAction 클래스 파일을 작성한다.

CalcAction.java

package struts.calc.action;

 

//import 정보 생략

 

public class CalcAction extends Action{

 

@Override

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

 

DynaActionForm dynaForm=(DynaActionForm)form;

//DynaActionForm.get(property이름: String): Object

// Or

//DynaActionForm.getMap() : Map <--일괄적으로 Return

//우선 전자의 방식으로 자료 가져오기

int operand1=(Integer)dynaForm.get("operand1");

int operand2=(Integer)dynaForm.get("operand2");

char operator=(Character)dynaForm.get("operator");

 

//계산하기

int result=calc(operand1, operand2, operator);

 

//위의 계산값을 dynaForm의 calcResult에 할당

//DynaActionForm.set(Property이름 : String, value: object)

dynaForm.set("calcResult",result);

return mapping.findForward("result");

}

 

public int calc(int op1,int op2, char operator){

int result=0;

switch(operator){

case '+':

result=op1+op2;

case '-':

result=op1-op2;

case '*':

result=op1+op2;

case '/':

result=op1+op2;

}

return result;

}

}

 

  • 결과값을 사용자에게 보여줄 calc_result.jsp 를 생성한다.

calc_result.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<html>

<head>

<title>Insert title here</title>

</head>

<body>

    ${requestScope.calcForm.map.operand1 }

    ${requestScope.calcForm.map.operator }

    ${requestScope.calcForm.map.operand2 }

    =

    ${requestScope.calcForm.map.calcResult }

    

</body>

</html>

 

'Java' 카테고리의 다른 글

Spring_message Project  (0) 2010.06.16
Spring 중간 점검 실습  (0) 2010.06.15
Spring 초간단 실습  (0) 2010.06.15
Filter  (0) 2010.06.13
File Upload API  (0) 2010.06.13
Spring에서 자주 사용되어지는 API 묶음  (0) 2010.06.13
간단한 Spring Project 실습하기  (0) 2010.06.13
Spring 설치 및 이클립스와의 연동  (1) 2010.06.13
Tomcat 설치 및 간단한 환경설정  (0) 2010.04.22
0401 Report Source  (0) 2010.04.01