자바 프로그래밍/Struts1 & Struts2

이번에는 글목록을 출력하는 코드를 작성해보도록 하겠다. 일단 모델은 지난 번과 같이 POJO를 사용하여 최대한 단순무식(?)하게 구현을 할 것이다. 데이터맵핑과 관련한 프레임워크를 사용해 볼 계획이지만 일단은 스트러츠 1.x에 최대한 집중하여 작성할 것이므로 다른 프레임워크를 섞어서 코드를 복잡하게 할 생각은 없다.^^;

모델

	private static final String _LIST = ""
		+ "SELECT no, title, writer, wtime FROM bboard ORDER BY no DESC "
		+ "LIMIT ?, ?";
	
	private static final int _ROWSPERPAGE = 10;

	/**
	 * 게시판 글목록 가져오기
	 * @param pageNo 페이지 번호
	 * @return ArrayList<BasicBoardDataBean> 글목록
	 * @throws SQLException
	 */
	public List<BasicBoardDataBean> list(int pageNo) throws SQLException {
		ArrayList<BasicBoardDataBean> rows =
			new ArrayList<BasicBoardDataBean>();
		int startRowNo = (pageNo - 1) * _ROWSPERPAGE + 1;
		int endRowNo = pageNo * _ROWSPERPAGE;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		conn = _getConnection();
		
		try {
			pstmt = conn.prepareStatement(_LIST);
			pstmt.setInt(1, startRowNo);
			pstmt.setInt(2, endRowNo);
			
			
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				BasicBoardDataBean row = new BasicBoardDataBean();
				row.setNo(rs.getLong(1));
				row.setTitle(rs.getString(2));
				row.setWriter(rs.getString(3));
				row.setWtime(rs.getTimestamp(4));
				
				rows.add(row);
			}
		} finally {
			try {
				pstmt.close();
			} catch (SQLException e) {
				throw e;
			}

			try {
				conn.close();
			} catch (SQLException e) {
				throw e;
			}
			
			pstmt = null;
			conn = null;
		}
		
		return rows;
	}

출력을 위한 폼이므로 ActionForm은 일단 작성하지 않았다. 스트러츠는 JSTL을 확장한 다양한 taglib를 제공한다. 우선 페이지 네비게이션과 디자인은 빼고 기본적인 로직만 담도록 하겠다.

폼(listForm.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %>
<%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html:html lang="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글목록</title>
</head>
<body>
<logic:empty name="rows" scope="request">
<p>글 목록이 없습니다.</p>
</logic:empty>
<logic:notEmpty name="rows" scope="request">
	<logic:iterate id="row" name="rows">
		<bean:write name="row" property="no"/>:
		<bean:write name="row" property="title"/>:
		<bean:write name="row" property="writer"/>:
		<bean:write name="row" property="wtime"
			format="yyyy년 MM월 dd월 hh시 mm분 ss초"/>
		<br>
	</logic:iterate>
</logic:notEmpty>
</body>
</html:html>

액션폼(ListAction.java)

package net.jeongsam.bboard.struts1.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeongsam.bboard.model.BasicBoardDAO;
import net.jeongsam.bboard.model.BasicBoardDataBean;

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 ListAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ActionForward forward = null;
		String $pageNo = request.getParameter("pageNo");
		int pageNo = Integer.parseInt(
				$pageNo != null ? $pageNo : "1");
		
		BasicBoardDAO boardMgr = new BasicBoardDAO();
		List rows = boardMgr.list(pageNo);
		
		request.setAttribute("rows", rows);
		forward = mapping.findForward("LIST");
		
		return forward;
	}
}

매핑설정(struts-config.xml)

	<action
			path="/list"
			type="net.jeongsam.bboard.struts1.action.ListAction"
			name="listForm"
			scope="request"
			validate="false">
			<forward name="LIST" path="/bboard/struts1/listForm.jsp"/>
	</action>

스트러츠는 JSP에서의 필터와 같은 기능을 RequestProcessor 클래스를 확장하는 방법으로 제공한다. 예를 들어 폼을 이용하여 데이터를 읽어들이는데 ActionForm을 이용하게 되면 한글 처리를 위해 인코딩 변경 코드를 넣을 곳이 마땅하지 않다. Action에 넣으면 되겠지만 만일 ActionForm에서 입력데이터의 검증시 한글을 처리해야 할 경우 역시 문제가 된다.

참고로 HTML-FORM에 입력된 데이터는 ActionForm으로 전달되어 입력 데이터의 검증을 거치고 Action을 통해 모델로 전달된다. 여기서 HTML-FORM과 ActionForm이 뷰가 되고 ActionServlet이라는 컨트롤러에 의해 적당한 Action이 호출되어 모델로 데이터를 전달하는데, 여기서는 2가지 이슈가 발생한다. 첫번째는 ActionForm자체가 빈이므로 ActionForm자체를 모델로 전달할 것이가 하는 문제인데 이는 유연성을 위해 데이터빈을 별도로 작성하여 ActionForm으로부터 데이터빈으로 데이터를 저장한 뒤 이 데이터빈을 모델로 전달하는 것이 원칙이다. 두번째는 Action을 컨트롤러로 볼 것인지 모델로 볼 것인지 하는 문제인데 이 문제는 스트러츠 프레임워크 제작팀과 MVC 패턴 신봉자들간의 문제로 남겨두는 것이 정신건강에 유익할 것 같다.

다시 원래의 문제로 돌아가서 한글 처리를 위한 코드를 어디에 넣느냐하는 문제가 남는데 이를 위해 RequestProcessor 클래스를 상속하여 확장할 필요가 있다. RequestProcessor 클래스에는 여러 메서드가 제공되는데 여기서는 processoPreprocess() 메서드를 오버라이딩하여 처리한다.

package net.jeongsam.bboard.struts1;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.RequestProcessor;

public class KoRequestProcessor extends RequestProcessor {
	@Override
	protected boolean processPreprocess(HttpServletRequest request,
			HttpServletResponse resoponse) {
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return true;
	}
}

스트러츠는 JSP의 모델2를 구현한 프레임워크이다. 현재는 스트러츠2로 새로이 바뀌었지만 관공서 등 기존 작성된 대부분의 프로젝트는 스트러츠1을 기반으로 작성된 것이 많으므로 스트러츠1을 기반으로 한 예제를 만들어 보려고 한다.

예제에 사용된 환경은 다음과 같다.

  • Tomcat 6.0.20
  • JSTL 1.2
  • Struts 1.3.10
  • Eclipse 3.5
  • MySQL 5.1

예제를 단순화시키기 위해 게시판은 기본적인 구조를 가지도록 스키마를 작성했다.

스키마는 JSP 모델1과 동일하다.

이클립스에서 실행시키기 위해 Struts 1.3 라이브러리를 프로젝트의 lib 폴더로 옮겨놓는다. 참고를 위해 프로젝트 탐색기의 구조를 캡쳐해서 올려놓았다.

스트러츠1은 입력폼(writeForm.jsp)과 입력폼의 데이터를 검증하기 위한 액션 폼(InsertForm.java), 그리고 입력폼의 데이터를 모델로 전달하는 액션(InsertAction.java)을 구현한다. 그리고 struts-config.xml을 통해 액션 폼과 폼, 액션을 연결하여 컨트롤러가 실행하도록 한다. 물론 컨드롤러의 배포기술자는 web.xml에 작성한다.

입력폼(writerForm.jsp) 소스

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html:html lang="true">
<head>
<title><bean:message key="writeform.title"/></title>
<html:base/>
<link href="${pageContext.request.contextPath}/bboard/css/writeForm.css"
	rel="stylesheet" type="text/css">
</head>
<body>
<h1><bean:message key="writeform.title"/></h1>
<html:form method="post" action="insert" lang="UTF-8" focus="title">
<table border="1">
<colgroup>
<col class="tableHeader">
<col>
</colgroup>
<tr>
<td colspan="2"><html:errors/></td>
</tr>
<tr>
<th><bean:message key="writeform.form.title"/></th>
<td><html:text property="title" size="50"/>
<html:errors property="title"/></td>
</tr>
<tr>
<th><bean:message key="writeform.form.writer"/></th>
<td><html:text property="writer" size="10"/>
<html:errors property="writer"/></td>
</tr>
<tr>
<th><bean:message key="writeform.form.content"/></th>
<td><html:errors property="content"/>
<html:textarea property="content" cols="50" rows="10"/>
</tr>
<tr>
<td colspan="2"><html:submit titleKey="writeform.form.submit"/></td>
</tr>
</table>
</html:form>
</body>
</html:html>

액션 폼(InsertForm.java) 소스

package net.jeongsam.bboard.struts1.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

@SuppressWarnings("serial")
public class InsertForm extends ActionForm {
	private String title;
	private String writer;
	private String content;
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		if (getTitle() == null || getTitle().length() == 0) {
			errors.add("title", new ActionMessage("writeform.error.title"));
		}
		if (getWriter() == null || getWriter().length() == 0) {
			errors.add("writer", new ActionMessage("writeform.error.writer"));
		}
		if (getContent() == null || getContent().length() == 0) {
			errors.add("content", new ActionMessage("writeform.error.content"));
		}
		
		return errors;
	}
}

액션(InsertAction.java) 소스

package net.jeongsam.bboard.struts1.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jeongsam.bboard.model.BasicBoardDAO;
import net.jeongsam.bboard.model.BasicBoardDataBean;
import net.jeongsam.bboard.struts1.form.InsertForm;

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 InsertAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response)
		throws Exception {
		
		BasicBoardDataBean bbRow = new BasicBoardDataBean();
		BasicBoardDAO boardMgr = new BasicBoardDAO();
		
		bbRow.setTitle(((InsertForm)form).getTitle());
		bbRow.setWriter(((InsertForm)form).getWriter());
		bbRow.setContent(((InsertForm)form).getContent());
		
		boardMgr.insert(bbRow);
		
		return mapping.findForward("Success");
	}
}

BasicBoard_ko_KR.properties

#Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net)

errors.footer = </ul>
errors.header = <ul>
errors.prefix = <li>
errors.suffix = </li>

writeform.error.content = 본문을 입력하세요.
writeform.error.title   = 제목을 입력하세요.
writeform.error.writer  = 저자를 입력하세요.
writeform.form.content  = 본문
writeform.form.title    = 제목
writeform.form.writer   = 저자
writeform.title         = 글쓰기

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
	"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
	<form-beans>
		<form-bean
			name="insertForm"
			type="net.jeongsam.bboard.struts1.form.InsertForm">
			<form-property name="" type=""></form-property>
		</form-bean>
	</form-beans>
	
	<action-mappings>
		<action
			name="insertForm"
			type="net.jeongsam.bboard.struts1.action.InsertAction"
			path="/insert"
			scope="request"
			validate="true"
			input="/bboard/struts1/writeForm.jsp">
			<forward name="Success" path="/bboard/struts1/result.jsp" redirect="true"/>
			<forward name="Fail" path="/bboard/struts1/writeForm.jsp"/>
		</action>
	</action-mappings>
	
	<controller
		processorClass="net.jeongsam.bboard.struts1.KoRequestProcessor"
		contentType="text/html;charset=UTF-8"
		locale="true"
		nocache="true"/>
		
    <message-resources
    	parameter="net.jeongsam.bboard.struts1.BasicBoard"
    	null="false"/>
</struts-config>

web.xml

<servlet>
		<servlet-name>Struts1Action</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts1-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Struts1Action</servlet-name>
		<url-pattern>/struts1/bboard/*</url-pattern>
	</servlet-mapping>

server.xml

<Context
	docBase="MySamples"
	path="/MySamples"
	reloadable="true"
	source="org.eclipse.jst.jee.server:MySamples">
	<Resource
		auth="Container"
		driverClassName="com.mysql.jdbc.Driver"
		maxActive="100"
		maxIdle="30"
		maxWait="10000"
		name="jdbc/MySamples"
		type="javax.sql.DataSource"
		url="jdbc:mysql://127.0.0.1:3306/example?autoReconnect=true"
		username="****"
		password="****"/>
</Context>

한가지 덧붙이자면, MVC 모델에서 컨트롤러는 사용자의 요청을 받아 뷰와 모델을 선택하는 단순한 기능만을 구현하도록 하고 있다. 그래서 스트러츠1에서도 액션 폼을 컨트롤러로 보아야 하는지 모델로 보아야 하는지에 대한 논의가 상당수 있는 듯하다. 원칙론자라면 액션 폼이 컨트롤러에 종속된 면이 없지않은 이유로 모델로 볼 수 없고, 게다가 같은 이유로 모델로 볼 수도 없다는 입장이며 그런 이유로 스트러츠는 완벽하게 이론적인 MVC를 구현했다고 볼 수 없다는 의견이 있다.

+ Recent posts