일반 Java 웹프로그래밍에서의 MVC.

 

  1. 사용자가 jsp(view) 페이지에 접근.
  2. 링크나 폼 등을 전송하여 서블릿에 요청.
  3. web.xml 에 맵핑된 서블릿(controller) 호출.
  4. 서블릿은 클래스(model)로부터 객체를 생성하고 처리 결과를 view로 보냄.
  5. 반환 값을 받은 jsp(view) 페이지를 사용자에게 출력.

 

Struts 에서의 MVC.

 

  1. 사용자가 jsp(view) 페이지에 접근.
  2. 링크나 폼 등을 전송하여 Action 클래스에 요청.
  3. struts.xml 에 맵핑된 Action 클래스(controller) 호출.
  4. Action 클래스는 클래스(model)로부터 객체를 생성하고 처리 결과를 view로 보냄.
  5. 반환 값을 받은 jsp(view) 페이지를 사용자에게 출력.

 

차이는 Servlet <-> Action 클래스인데... 왜 굳이 Struts를... ㅜㅜ

 

index.action 페이지에서 action 링크를 클릭하면,
Action 클래스에서 결과를 hello.action 으로 보내는 프로세스를 구현해 봅니다.

 

 

1. model 생성 (src/main/java)

 

우선 view 페이지에 메시지가 출력되도록 POJO java(model) 파일을 작성합니다.
model 클래스는 JavaBean 스타일에 따라 set/get 메소드를 사용하여 작성합니다.

 

file: MessageStore.java

package com.oops4u.web.helloworld.model;

public class MessageStore {

    private String message;

    public MessageStore() {
        setMessage( "Hello Struts User" );
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage( String message ) {
        this.message = message;
    }
}

 

MessageStore 객체를 생성하면 멤버 변수(message)에 "Hello Struts User" 가 저장될 것이고,
set~ 로 새메시지를 저장하거나 get~ 로 반환할 수 있습니다.

 

 

2. Controller(Action) 생성(src/main/java)

 

view 페이지에서 클릭 등으로 호출할 action 클래스 입니다.
model 클래스에서 결과값을 가져와 view 페이지로 렌더링 합니다.

 

file: HelloWorldAction.java

package com.oops4u.web.helloworld.action;

import com.oops4u.web.helloworld.model.MessageStore;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private MessageStore messageStore;
   
    public String execute() throws Exception {
       messageStore = new MessageStore();
       return SUCCESS;
    }
   
    public MessageStore getMessageStore() {
       return messageStore;
    }
   
    public void setMessageStore( MessageStore messageStore ) {
       this.messageStore = messageStore;
    }
}

위에 작성한 Model 과 com.opensymphony.xwork2.ActionSupport 클래스를 import 합니다.
그리고 ActionSupport 로부터 상속받으면 Action 클래스는 SUCCESS, ERROR, INPUT 처럼 결과를 반환할 수 있습니다.
private static final long serialVersionUID = 1L;
이건 직렬화랑 연관된 듯한데 잘 모르겠고, 암튼 JVM에서 UID를 자동 생성하란 뜻입니다.ㅋ
위에서는 execute 메소드가 model 클래스의 객체 생성과 SUCCESS 값을 반환합니다.

 

 

3. 출력될 View 생성(src/main/webapp)

 

Action 클래스에서 저장된 문자열을 출력할 view 를 생성합니다.
이것은 링크로부터 Action 클래스가 실행된 후 결과를 나타낼 페이지 입니다.

 

file: HelloWorld.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello World!</title>
</head>
<body>
    <h2><s:property value="messageStore.message" /></h2>
</body>
</html>

 

Struts 태그 라이브러리를 사용하여 속성값을 출력합니다.
<s:property />의 속성 값에서 messageStore는 Action 클래스에서 생성된 객체이며 message 는 객체의 멤버변수(문자열)입니다.
결과는 "Hello Struts User" 가 보여지겠네요.
어떻게 HelloWorldAction의 execute 메소드가 실행되고 결과 페이지인 HelloWorld.jsp 를 렌더링 하는지는
struts.xml 파일에서 Action에 대한 맵핑 설정을 수정하면 됩니다.

 

 

4. Struts 구성 (src/main/resources)

 

struts.xml 파일에 Action 클래스와 view 페이지와의 URL의 맵핑이 필요합니다.

 

<?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>
    <constant name="struts.devMode" value="true" />
    <package name="basicstruts2" extends="struts-default">
        <action name="index">
            <result>/index.jsp</result>
        </action>
 
        <action name="hello" class="com.oops4u.web.helloworld.action.HelloWorldAction" method="execute">
            <result name="success">/HelloWorld.jsp</result>
        </action>

    </package>
</struts>

 

hello.action이 호출되면 HelloWorldAction의 execute메소드를 실행하고 반환값이 success이면 HelloWorld.jsp 파일을 렌더링 하도록 작성하였습니다.

 

 

5. Index 페이지 수정 (index.jsp)

 

hello Action 클래스의 execute 메소드를 실행하도록 페이지에 링크를 추가합니다.

 

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
    <p><a href="<s:url action='hello'/>">Hello World</a></p>
</body>
</html>

 

굳이 태그 라이브러리를 사용하였습니다 ^^
위 url 태그는 hello.action 으로의 링크를 생성합니다.
배포하고나면 index.jsp 파일에서 링크를 클릭하면 hello.action 이 실행되며 "Hello Struts User" 를 나타낼 것입니다.


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,