1.게시판에 사용될 테이블 만들기
sql
CREATE TABLE board( seq int auto_increment primary key, //글번호 writer varchar(20) not null, // 글쓴이 title varchar(100) not null, // 글제목 content mediumtext, //글내용 pwd varchar(20) not null, // 글 비밀번호 hit decimal(5,0) not null, // 조회수 groups decimal(10,0) not null, //글 그룹(답글 용) step decimal(3,0) not null, //답글의 순서 level decimal(3,0) not null, //첫번째 답글이냐 두번째 답글이냐 bname varchar(10) not null, // 게시판 이름** bname="식물" bname="물고기" regdate datetime not null //글 등록시간 ); 컬럼 수정 alter table board modify column regdate datetime not null;[#M_Sql|접기|
CREATE TABLE board( seq int auto_increment primary key, writer varchar(20) not null, title varchar(100) not null, content mediumtext, pwd varchar(20) not null, hit decimal(5,0) not null, groups decimal(10,0) not null, step decimal(3,0) not null, level decimal(3,0) not null, bname varchar(10) not null, regdate datetime not null ); alter table board modify column regdate datetime not null;
<?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>Chapter14</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> <init-param> <param-name>struts.i18n.encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/> <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=euckr"/> <property name="JDBC.Username" value="root"/> <property name="JDBC.Password" value="1234"/> </dataSource> </transactionManager> <sqlMap resource="Board.xml" /> </sqlMapConfig>
Board.xml(SQL 구문 매핑하기)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd"> <sqlMap> <typeAlias alias="Board" type="com.board.model.BoardVo"/> <!-- 리절트 맵 정의 --> <resultMap id="BoardResult" class="Board" > <result property="seq" column="seq" columnIndex="1"/> <result property="writer" column="writer" columnIndex="2"/> <result property="title" column="title" columnIndex="4"/> <result property="content" column="content" columnIndex="5"/> <result property="pwd" column="pwd" columnIndex="6"/> <result property="hit" column="hit" columnIndex="7"/> <result property="groups" column="groups" columnIndex="8"/> <result property="step" column="step" columnIndex="9"/> <result property="level" column="level" columnIndex="10"/> <result property="bname" column="bname" columnIndex="11"/> <result property="regdate" column="regdate" columnIndex="12"/> </resultMap> <select id="BoardList" parameterClass="java.util.Map" resultMap="BoardResult"> select seq, writer, title, content, pwd, hit, groups, step, level, bname, regdate from board <dynamic prepend="where"> <isNotEmpty prepend="AND" property="bname"> bname = #bname# </isNotEmpty> <isNotEmpty prepend="AND" property="seq"> seq = #seq# </isNotEmpty> <isNotEmpty prepend="AND" property="title"> title = #title# </isNotEmpty> <isNotEmpty prepend="AND" property="content"> content = #content# </isNotEmpty> <isNotEmpty prepend="AND" property="writer"> writer = #writer# </isNotEmpty> </dynamic> order by groups desc , step asc <isNotEmpty property="start"> <isNotEmpty property="end"> limit $start$, $end$ </isNotEmpty> </isNotEmpty> </select> <select id="BoardOne" parameterClass="java.util.Map" resultMap="BoardResult"> select * from board where seq = #seq# AND bname = #bname# </select> <select id="BoardCnt" parameterClass="java.util.Map" resultClass="Integer"> select count(*) from board <dynamic prepend="where"> <isNotEmpty prepend="AND" property="bname"> bname = #bname# </isNotEmpty> </dynamic> </select> <insert id="BoardInsert" parameterClass="Board"> insert into board ( seq, writer, title, content, pwd, hit, groups, step, level, bname, regdate ) values ( #seq#, #writer#, #title#, #content#, #pwd#, 0, #groups#, #step#, #level#, #bname#, now() ) </insert> <select id="BoardMaxSeq" resultClass="Integer"> select ifnull(max(seq),0) from board </select> <update id='BoardStepUpdate' parameterClass="java.util.Map"> update board set step=step+1 where groups = #groups# and step > #step# </update> <update id='BoardHitUpdate' parameterClass="java.util.Map"> update board set hit=hit+1 where seq = #seq# </update> <update id='BoardUpdate' parameterClass="Board"> update board set writer = #writer# , title = #title# , content = #content#, pwd = #pwd# , regdate = now() where seq = #seq# </update> <delete id="BoardDelete" parameterClass="Integer"> delete from board where seq = #value# </delete> </sqlMap>
package com.board.model; public class BoardVo { private int seq; private String writer; private String title; private String content; private String pwd; private int hit; private int groups; private int step; private int level; private String bname; private String regdate; public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getHit() { return hit; } public void setHit(int hit) { this.hit = hit; } public int getGroups() { return groups; } public void setGroups(int groups) { this.groups = groups; } public int getStep() { return step; } public void setStep(int step) { this.step = step; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public String getRegdate() { return regdate; } public void setRegdate(String regdate) { this.regdate = regdate; } }
textarea {color:#000000; font-family:"굴림"; font-size:9pt; line-height:120%;background-color: #FFFFFF; border: 1 solid #999999} td { color:#3f3f3f; font-family:"굴림"; font-size:9pt; line-height:170%;} td a { color:#333377; font-family:"굴림"; font-size:9pt; line-height:170% ; text-decoration: none; } td a:hover { color:#3366CC; font-family:"굴림"; font-size:9pt; line-height:170% ; text-decoration: underline;} input {color:#000000; font-family:"굴림"; font-size:9pt; line-height:120%;background-color: #FFFFFF; border: 1 solid #999999} .inputb {BORDER-BOTTOM: #999999 1px solid; BORDER-LEFT: #cecece 1px solid;BORDER-RIGHT: #999999 1px solid; BORDER-TOP: #cecece 1px solid; COLOR: #000000; FONT-SIZE: 9pt;background-color: #EDEDED;}
com.util.SqlMapLocator.java
package com.util; import java.io.IOException; import java.io.Reader; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; public class SqlMapLocator { public static SqlMapClient getMapper(){ SqlMapClient sqlMapper; try { Reader reader = Resources.getResourceAsReader( "SqlMapConfig.xml"); sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (IOException e) { // Fail fast. throw new RuntimeException( "Something bad happened while building the SqlMapClient instance." + e, e); } return sqlMapper; } }
package com.board.dao; import java.sql.SQLException; import java.util.List; import com.board.model.BoardVo; import com.util.SqlMapLocator; public class BoardDao { private static BoardDao singleton; private BoardDao() { } public static BoardDao getInstance() { if (singleton == null) singleton = new BoardDao(); return singleton; } public List<BoardVo> list(Object obj) throws SQLException { List<BoardVo> list = SqlMapLocator.getMapper().queryForList("BoardList", obj); return list; } public void insert(Object obj) throws SQLException { SqlMapLocator.getMapper().insert("BoardInsert", (BoardVo)obj); } public BoardVo selectBoard(Object obj) throws SQLException { BoardVo vo=(BoardVo)SqlMapLocator.getMapper().queryForObject("BoardOne", obj); return vo; } public int getMaxSeq() throws SQLException { return ((Integer)SqlMapLocator.getMapper() .queryForObject("BoardMaxSeq")).intValue(); } public void updateStep(Object obj) throws SQLException { SqlMapLocator.getMapper().update("BoardStepUpdate",obj); } public void updateHit(Object obj)throws SQLException{ SqlMapLocator.getMapper().update("BoardHitUpdate",obj); } public void update(Object obj)throws SQLException{ SqlMapLocator.getMapper().update("BoardUpdate",obj); } public void delete(Object obj)throws SQLException{ SqlMapLocator.getMapper().delete("BoardDelete",obj); } public int getRowCount(Object obj) throws SQLException { return ((Integer)SqlMapLocator.getMapper().queryForObject("BoardCnt", obj)).intValue(); } }
sturts.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> <constant name="struts.i18n.encoding" value="UTF-8" /> <constant name="struts.devMode" value="true" /> <!-- 용량제한 100MB 로 설정. --> <constant name="struts.multipart.maxSize" value="104857600" /> <package name="board" namespace="/" extends="struts-default"> <!-- 글로벌 예외 처리 화면 설정 --> <global-results> <result name="error">/jsp/board/pageError.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="error" exception="java.lang.Exception"/> </global-exception-mappings> <!-- 게시판 리스트 액션 --> <action name="listAction" class="action.board.ListAction"> <result>/jsp/board/boardList.jsp</result> </action> <!-- 게시판 쓰기 액션 --> <action name="writeFormAction" class="action.board.WriteAction" method="form"> <result>/jsp/board/boardWrite.jsp</result> </action> <action name="writeAction" class="action.board.WriteAction"> <result type="redirect-action"> <param name="actionName">listAction</param> </result> </action> <!-- 게시판 상세보기 액션. --> <action name="viewAction" class="action.board.ViewAction"> <interceptor-ref name="prepare"/> <interceptor-ref name="modelDriven"/> <interceptor-ref name="params"/> <result>/jsp/board/boardView.jsp</result> </action> <!-- 비밀번호 체크 액션. --> <action name="checkFormAction" class="action.board.ViewAction" method="checkForm"> <result>/jsp/board/checkPassword.jsp</result> </action> <action name="checkAction" class="action.board.ViewAction" method="checkAction"> <result name="error">/jsp/board/checkError.jsp</result> <result>/jsp/board/checkSuccess.jsp</result> </action> <!-- 게시판 수정 액션. --> <action name="modifyFormAction" class="action.board.ViewAction"> <result type="chain">writeFormAction</result> </action> <action name="modifyAction" class="action.board.ModifyAction"> <result type="chain">viewAction</result> </action> <!-- 게시판 삭제 액션. --> <action name="deleteAction" class="action.board.DeleteAction"> <result type="chain">listAction</result> </action> </package> </struts>
action.board.PagingAction.java(페이지 처리 클래스)
package action.board; public class PagingAction { private int currentPage; // 현재페이지 private int totalCount; // 전체 게시물 수 private int totalPage; // 전체 페이지 수 private int blockCount; // 한 페이지의 게시물의 수 private int blockPage; // 한 화면에 보여줄 페이지 수 private int startCount; // 한 페이지에서 보여줄 게시글의 시작 번호 private int endCount; // 한 페이지에서 보여줄 게시글의 끝 번호 private int startPage; // 시작 페이지 private int endPage; // 마지막 페이지 private StringBuffer pagingHtml; // 페이징 생성자 public PagingAction(int currentPage, int totalCount, int blockCount, int blockPage) { this.blockCount = blockCount; this.blockPage = blockPage; this.currentPage = currentPage; this.totalCount = totalCount; // 전체 페이지 수 totalPage = (int) Math.ceil((double) totalCount / blockCount); if (totalPage == 0) { totalPage = 1; } // 현재 페이지가 전체 페이지 수보다 크면 전체 페이지 수로 설정 if (currentPage > totalPage) { currentPage = totalPage; } // 현재 페이지의 처음과 마지막 글의 번호 가져오기. startCount = (currentPage - 1) * blockCount; endCount = startCount + blockCount - 1; // 시작 페이지와 마지막 페이지 값 구하기. startPage = (int) ((currentPage - 1) / blockPage) * blockPage + 1; endPage = startPage + blockPage - 1; // 마지막 페이지가 전체 페이지 수보다 크면 전체 페이지 수로 설정 if (endPage > totalPage) { endPage = totalPage; } // 이전 block 페이지 pagingHtml = new StringBuffer(); if (currentPage > blockPage) { pagingHtml.append("<a href=listAction.action?currentPage=" + (startPage - 1) + ">"); pagingHtml.append("이전"); pagingHtml.append("</a>"); } pagingHtml.append(" | "); //페이지 번호.현재 페이지는 빨간색으로 강조하고 링크를 제거. for (int i = startPage; i <= endPage; i++) { if (i > totalPage) { break; } if (i == currentPage) { pagingHtml.append(" <b> <font color='red'>"); pagingHtml.append(i); pagingHtml.append("</font></b>"); } else { pagingHtml .append(" <a href='listAction.action?currentPage="); pagingHtml.append(i); pagingHtml.append("'>"); pagingHtml.append(i); pagingHtml.append("</a>"); } pagingHtml.append(" "); } pagingHtml.append(" | "); // 다음 block 페이지 if (totalPage - startPage >= blockPage) { pagingHtml.append("<a href=listAction.action?currentPage=" + (endPage + 1) + ">"); pagingHtml.append("다음"); pagingHtml.append("</a>"); } } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getBlockCount() { return blockCount; } public void setBlockCount(int blockCount) { this.blockCount = blockCount; } public int getBlockPage() { return blockPage; } public void setBlockPage(int blockPage) { this.blockPage = blockPage; } public int getStartCount() { return startCount; } public void setStartCount(int startCount) { this.startCount = startCount; } public int getEndCount() { return endCount; } public void setEndCount(int endCount) { this.endCount = endCount; } public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; } public int getEndPage() { return endPage; } public void setEndPage(int endPage) { this.endPage = endPage; } public StringBuffer getPagingHtml() { return pagingHtml; } public void setPagingHtml(StringBuffer pagingHtml) { this.pagingHtml = pagingHtml; } }
action.board.ListAction.java
package action.board; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.board.dao.BoardDao; import com.board.model.BoardVo; import com.opensymphony.xwork2.ActionSupport; public class ListAction extends ActionSupport { private BoardDao dao; private String bname="bbs"; //게시판 이름 private List<BoardVo> list = new ArrayList<BoardVo>(); // <s:iterator value="list" private int currentPage = 1; // 현재 페이지 private int totalCount; // 총 게시물의 수 private int blockCount = 10; // 한 페이지의 게시물의 수 private int blockPage = 5; // 한 화면에 보여줄 페이지 수 private String pagingHtml; // 페이징을 구현한 HTML private PagingAction page; // 페이징 클래스 // 생성자 public ListAction() throws IOException { dao = BoardDao.getInstance(); } // 게시판 LIST 액션 public String execute() throws Exception { HashMap map = new HashMap(); map.put("bname",bname); totalCount = dao.getRowCount(map); // 전체 글 갯수를 구한다. page = new PagingAction(currentPage, totalCount, blockCount, blockPage); // PagingAction 객체 생성. pagingHtml = page.getPagingHtml().toString(); // 페이지 HTML 생성. // 현재 페이지에서 보여줄 마지막 글의 번호 설정. int lastCount = totalCount; // 현재 페이지의 마지막 글의 번호가 전체의 마지막 글 번호보다 작으면 lastCount를 +1 번호로 설정. if (page.getEndCount() < totalCount) lastCount = page.getEndCount() + 1; // 현재 페이지만큼의 게시물 리스트를 가져온다. map.put("start", page.getStartCount()); map.put("end", lastCount); list = dao.list(map); return SUCCESS; } public List<BoardVo> getList() { return list; } public void setList(List<BoardVo> list) { this.list = list; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getBlockCount() { return blockCount; } public void setBlockCount(int blockCount) { this.blockCount = blockCount; } public int getBlockPage() { return blockPage; } public void setBlockPage(int blockPage) { this.blockPage = blockPage; } public String getPagingHtml() { return pagingHtml; } public void setPagingHtml(String pagingHtml) { this.pagingHtml = pagingHtml; } public PagingAction getPage() { return page; } public void setPage(PagingAction page) { this.page = page; } }
board.boardList.jsp(글 목록을 위한 JSP 페이지)
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>스트럿츠2 게시판</title> <link rel="stylesheet" href="../css/board.css" type="text/css"> </head> <body> <br> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <tr> <td align="center"><h3>스트럿츠2 게시판</h3></td> </tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <tr align="center" bgcolor="#F3F3F3"> <td width="50"><strong>번호</strong></td> <td><strong>제목</strong></td> <td width="70"><strong>글쓴이</strong></td> <td width="80"><strong>날짜</strong></td> <td width="50"><strong>조회</strong></td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="5"></td> </tr> <s:iterator value="list" status="stat"> <s:url id="viewURL" action="viewAction" > <s:param name="seqarg"> <s:property value="seq" /> </s:param> <s:param name="currentPage"> <s:property value="currentPage" /> </s:param> </s:url> <tr bgcolor="#FFFFFF" align="center"> <td><s:property value="seq" /></td> <td align="left"> <s:a href="%{viewURL}"> <s:property value="title" /> </s:a> </td> <td align="center"><s:property value="writer" /></td> <td align="center"><s:property value="regdate" /></td> <td><s:property value="hit" /></td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="5"></td> </tr> </s:iterator> <s:if test="list.size() <= 0"> <tr bgcolor="#FFFFFF" align="center"> <td colspan="5">등록된 게시물이 없습니다.</td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="5"></td> </tr> </s:if> <tr align="center"> <td colspan="5"> <s:property value="pagingHtml" escape="false" /> </td> </tr> <tr align="right"> <td colspan="5"> <input type="button" value="글쓰기" class="inputb" onClick= "javascript:location.href='writeFormAction.action?currentPage=<s:property value="currentPage" />'"> </td> </tr> </table> </body> </html>
struts.xml
<!-- 게시판 쓰기 액션 --> <action name="writeFormAction" class="action.board.WriteAction" method="form"> <result>/jsp/board/boardWrite.jsp</result> </action> <action name="writeAction" class="action.board.WriteAction"> <result type="redirect-action"> <param name="actionName">listAction</param> </result> </action>
package action.board; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import com.board.dao.BoardDao; import com.board.model.BoardVo; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.Preparable; import com.opensymphony.xwork2.ModelDriven; public class WriteAction extends ActionSupport implements Preparable, ModelDriven { private BoardDao dao; private String bname="bbs"; //게시판 이름 private BoardVo boardVo; private int currentPage; //현재 페이지 private int seq; private int group = 0; private int step = 0; private int level = 0; private Calendar today; public WriteAction() { dao = BoardDao.getInstance(); today = Calendar.getInstance(); //오늘 날짜 구하기. } public String form() throws Exception { //등록 폼. return SUCCESS; } // 게시판 WRITE 액션 @Override public String execute() throws Exception { int seq = dao.getMaxSeq()+1; if(boardVo.getSeq() == 0 ){ group = seq; step = 0; level = 0; }else{ group = boardVo.getGroups(); step = boardVo.getSeq()+1; Map map = new HashMap(); map.put("groups",group); map.put("step",step); dao.updateStep(map); level = boardVo.getLevel() + 1; } boardVo.setBname(bname); boardVo.setSeq(seq); boardVo.setGroups(group); boardVo.setStep(step); boardVo.setLevel(level); dao.insert(boardVo); return SUCCESS; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } @Override public void prepare() throws Exception { boardVo = new BoardVo(); } @Override public Object getModel() { return boardVo; } }
board.boarWrite.jsp(글 쓰기를 위한 JSP페이지)
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>스트럿츠2 게시판</title> <link rel="stylesheet" href="../css/board.css" type="text/css" /> <SCRIPT type="text/javascript"> function validation() { var frm = document.forms[0]; if(frm.subject.value == "") { alert("제목을 입력해주세요."); return false; } else if(frm.writer.value == "") { alert("이름을 입력해주세요."); return false; } else if(frm.pwd.value == "") { alert("비밀번호를 입력해주세요."); return false; } else if(frm.content.value == "") { alert("내용을 입력해주세요."); return false; } return true; } </SCRIPT> </head> <body> <center> <table width="600" border="0" cellspacing="0" cellpadding="2"> <tr> <td align="center"><h3>스트럿츠2 게시판</h3></td> </tr> </table> <s:if test="boardVo==null"> <form action="writeAction.action" method="post" onsubmit="return validation();"> </s:if> <s:else> <form action="modifyAction.action" method="post" > <s:hidden name="currentPage" value="%{currentPage}" /> <s:hidden name="seqarg" value="%{seqarg}" /> </s:else> <table width="600" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="right" colspan="2"> <font color="#FF0000">*</font>는 필수 입력사항입니다. </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td width="100" bgcolor="#F4F4F4"> <font color="#FF0000">*</font> 제목 </td> <td width="500" bgcolor="#FFFFFF"> <s:textfield name="title" theme="simple" maxlength="50" value="%{boardVo.title}" cssStyle="width:370px"/> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"><font color="#FF0000">*</font> 이름 </td> <td bgcolor="#FFFFFF"> <s:textfield name="writer" theme="simple" maxlength="20" value="%{boardVo.writer}" cssStyle="width:100px" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"><font color="#FF0000">*</font> 비밀번호 </td> <td bgcolor="#FFFFFF"> <s:password name="pwd" theme="simple" maxlength="20" value="%{boardVo.pwd}" cssStyle="width:100px" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"><font color="#FF0000">*</font> 내용 </td> <td bgcolor="#FFFFFF"> <s:textarea name="content" theme="simple" value="%{boardVo.content}" cols="50" rows="10" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr> <td align="right" colspan="2"> <input name="submit" type="submit" value="작성완료" class="inputb"> <input name="list" type="button" value="목록" class="inputb" onClick= "javascript:location.href='listAction.action?currentPage=<s:property value="currentPage" />'"> </td> </tr> </table> </form> </center> </body> </html>
5.게시물 상세보기
struts.xml
<!-- 게시판 상세보기 액션. --> <action name="viewAction" class="action.board.ViewAction"> <interceptor-ref name="prepare"/> <interceptor-ref name="modelDriven"/> <interceptor-ref name="params"/> <result>/jsp/board/boardView.jsp</result> </action> <!-- 비밀번호 체크 액션. --> <action name="checkFormAction" class="action.board.ViewAction" method="checkForm"> <result>/jsp/board/checkPassword.jsp</result> </action> <action name="checkAction" class="action.board.ViewAction" method="checkAction"> <result name="error">/jsp/board/checkError.jsp</result> <result>/jsp/board/checkSuccess.jsp</result> </action>action.board.ViewAction.java
jsp.board.boardView.jsp(게시물 상세보기를 위한 JSP페이지)package action.board; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.board.dao.BoardDao; import com.board.model.BoardVo; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class ViewAction extends ActionSupport implements Preparable, ModelDriven { private BoardDao dao; private String bname="bbs"; //게시판 이름 private BoardVo boardVo; private int currentPage; private int seqarg; private String pwdarg; public ViewAction() { dao = BoardDao.getInstance(); } // 상세보기 public String execute() throws Exception { Map map = new HashMap(); map.put("bname", bname); map.put("seq", seqarg); // 해당 글의 조회수 +1. dao.updateHit(map); // 해당 번호의 글을 가져온다. boardVo = dao.selectBoard(map); return SUCCESS; } // 비밀번호 체크 폼 public String checkForm() throws Exception { return SUCCESS; } // 비밀번호 체크 액션 public String checkAction() throws Exception { Map map = new HashMap(); map.put("bname", bname); map.put("seq", seqarg); // 해당 번호의 글을 가져온다. boardVo = dao.selectBoard(map); // 입력한 비밀번호가 틀리면 ERROR 리턴. if (boardVo.getPwd().equals(pwdarg) == false) return ERROR; return SUCCESS; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getSeqarg() { return seqarg; } public void setSeqarg(int seqarg) { this.seqarg = seqarg; } public String getPwdarg() { return pwdarg; } public void setPwdarg(String pwdarg) { this.pwdarg = pwdarg; } @Override public void prepare() throws Exception { boardVo = new BoardVo(); } @Override public Object getModel() { return boardVo; } public BoardVo getBoardVo() { return boardVo; } public void setBoardVo(BoardVo boardVo) { this.boardVo = boardVo; } }
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>스트럿츠2 게시판</title> <link rel="stylesheet" href="../css/board.css" type="text/css" /> <SCRIPT type="text/javascript"> function open_win_noresizable (url, name) { var oWin = window.open(url, name, "scrollbars=no,status=no,resizable=no,width=300,height=100"); } </SCRIPT> </head> <body> <center> <table width="600" border="0" cellspacing="0" cellpadding="2"> <tr> <td align="center"><h3>스트럿츠2 게시판</h3></td> </tr> <tr> <td height="20"></td> </tr> </table> <table width="600" border="0" cellspacing="0" cellpadding="0"> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"> 번호 </td> <td bgcolor="#FFFFFF"> <s:property value="seqarg" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td width="100" bgcolor="#F4F4F4"> 제목</td> <td width="500" bgcolor="#FFFFFF"> <s:property value="boardVo.title" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"> 글쓴이 </td> <td bgcolor="#FFFFFF"> <s:property value="boardVo.writer" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"> 내용 </td> <td bgcolor="#FFFFFF"> <s:property value="boardVo.content" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"> 조회수 </td> <td bgcolor="#FFFFFF"> <s:property value="boardVo.hit" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td bgcolor="#F4F4F4"> 등록날짜 </td> <td bgcolor="#FFFFFF"> <s:property value="boardVo.regdate" /> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr> <td align="right" colspan="2"> <s:url id="modifyURL" action="modifyForm" > <s:param name="seq"> <s:property value="seqarg" /> </s:param> </s:url> <s:url id="deleteURL" action="deleteAction" > <s:param name="seq"> <s:property value="seqarg" /> </s:param> </s:url> <input name="list" type="button" value="수정" class="inputb" onClick="javascript:open_win_noresizable('checkFormAction.action?seqarg=<s:property value="seqarg" />¤tPage=<s:property value="currentPage" />','modify')"> <input name="list" type="button" value="삭제" class="inputb" onClick="javascript:open_win_noresizable('checkFormAction.action?seqarg=<s:property value="seqarg" />¤tPage=<s:property value="currentPage" />','delete')"> <input name="list" type="button" value="목록" class="inputb" onClick="javascript:location.href='listAction.action?currentPage=<s:property value="currentPage" />'"> </td> </tr> </table> </center> </body> </html>jsp.board.checkPassword.java(비밀번호 체크를 위한)
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>비밀번호 확인</title> <link rel="stylesheet" href="../css/board.css" type="text/css" /> </head> <body> <center> <h2>비밀번호 확인</h2> <form action="checkAction.action" method="post"> <s:hidden name="seqarg" value="%{seqarg}" /> <s:hidden name="currentPage" value="%{currentPage}" /> <table width="250" border="0" cellspacing="0" cellpadding="0"> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> <tr> <td width="100" bgcolor="#F4F4F4"> 비밀번호 입력</td> <td width="150" bgcolor="#FFFFFF"> <s:password name="pwdarg" theme="simple" cssStyle="width:100px" maxlength="20"/> <input name="submit" type="submit" value="확인" class="inputb"> </td> </tr> <tr bgcolor="#777777"> <td height="1" colspan="2"></td> </tr> </table> </form> </center> </body> </html>
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>비밀번호 오류</title> <link rel="stylesheet" href="/board/common/css/css.css" type="text/css"> <script type="text/javascript"> function ErrorMessage() { alert("비밀번호가 틀립니다."); history.back(-1); } </script> </head> <body> <script>ErrorMessage()</script> </body> </html>jsp.board.checkSuccess.jsp
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>비밀번호 확인</title> <link rel="stylesheet" href="../css/board.css" type="text/css"> <SCRIPT type="text/javascript"> function locationURL() { if ( window.name == 'modify' ) window.opener.parent.location.href= 'modifyFormAction.action?seqarg=<s:property value="seqarg" />¤tPage=<s:property value="currentPage" />'; else if ( window.name == 'delete' ) { alert('삭제되었습니다.'); window.opener.parent.location.href= 'deleteAction.action?seq=<s:property value="seqarg" />¤tPage=<s:property value="currentPage" />'; } window.close(); } </SCRIPT> </head> <body> <script>locationURL()</script> </body> </html>
06.게시물 수정하기
struts.xml
<!-- 게시판 수정 액션. --> <action name="modifyFormAction" class="action.board.ViewAction"> <result type="chain">writeFormAction</result> </action> <action name="modifyAction" class="action.board.ModifyAction"> <result type="chain">viewAction</result> </action>action.boatrd.ModifyAction.java
package action.board; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.board.dao.BoardDao; import com.board.model.BoardVo; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class ModifyAction extends ActionSupport implements Preparable, ModelDriven { private BoardDao dao; private BoardVo boardVo; private int seqarg; private int currentPage; //현재 페이지 // 생성자 public ModifyAction() { dao = BoardDao.getInstance(); } // 게시글 수정 @Override public String execute() throws Exception { boardVo.setSeq(seqarg); dao.update(boardVo); return SUCCESS; } public int getSeqarg() { return seqarg; } public void setSeqarg(int seqarg) { this.seqarg = seqarg; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public void prepare() throws Exception { boardVo = new BoardVo(); } public Object getModel() { return boardVo; } public BoardVo getBoardVo() { return boardVo; } public void setBoardVo(BoardVo boardVo) { this.boardVo = boardVo; } }
07.게시물 삭제하기
struts.xml
<!-- 게시판 삭제 액션. --> <action name="deleteAction" class="action.board.DeleteAction"> <result type="chain">listAction</result> </action>
actioin.board.DeleteAction.java
package action.board; import java.io.IOException; import com.board.dao.BoardDao; import com.board.model.BoardVo; import com.opensymphony.xwork2.ActionSupport; public class DeleteAction extends ActionSupport { private BoardDao dao; private String bname="bbs"; //게시판 이름 private BoardVo vo; private int currentPage; //현재 페이지 private int seq; // 생성자 public DeleteAction() throws IOException { dao = BoardDao.getInstance(); } // 게시글 글 삭제 public String execute() throws Exception { dao.delete(seq); return SUCCESS; } public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
08.예외 처리 페이지
jsp.board.page.Error.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>게시판 오류 발생</title> <link rel="stylesheet" href="../css/board.css" type="text/css"> </head> <body> <h2>게시판 오류 발생</h2> <table width="600" border="0" cellspacing="0" cellpadding="0"> <tr> <td> 게시판에 오류가 발생했습니다. 관리자에게 문의바랍니다.</td> </tr> <tr> <td> </td> </tr> <tr> <td> <a href="listAction.action">리스트 화면으로 이동</a>.</td> </tr> </table> </body> </html>
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> <constant name="struts.i18n.encoding" value="UTF-8" /> <constant name="struts.devMode" value="true" /> <!-- 용량제한 100MB 로 설정. --> <constant name="struts.multipart.maxSize" value="104857600" /> <package name="board" namespace="/" extends="struts-default"> <!-- 글로벌 예외 처리 화면 설정 --> <global-results> <result name="error">/jsp/board/pageError.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="error" exception="java.lang.Exception"/> </global-exception-mappings> </package> </struts>
'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글
4일차 iBatis (0) | 2012.06.08 |
---|---|
4일차 스프링과 스트러츠로 회원가입 처리 (0) | 2012.06.08 |
4일차 Exception, Logging , Profiling (0) | 2012.06.08 |
4일차 단일 파일 업로드, 다중 파일 업로드 (0) | 2012.06.08 |
4일차 chain result type (0) | 2012.06.08 |