Dev/Spring

Spring2.5 - 게시판 만들기

창문닦이 2019. 4. 8. 16:07

게시글 작성 기능

1. 테이블 생성

create table sbbs

(boardNum number(9) not null,

name varchar2(20) not null,

pwd varchar2(10),

email varchar2(50),

subject varchar2(50) not null,

content varchar2(4000) not null,

ipAddr varchar2(20) not null,

hitCount number(9) not null,

created date,

constraint pk_sbbs_boardNum primary key(boardNum));

2. jsp 페이지 생성(View)

<%@ 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>게 시 판</title>

<link rel="stylesheet" href="<%=cp %>/board/css/style.css" type="text/css" />

<link rel="stylesheet" href="<%=cp %>/board/css/created.css" type="text/css" />

<script type="text/javascript" src="<%=cp %>/board/js/util.js"></script>

<script type="text/javascript" >

function sendIt(){

f = document.myForm;

str = f.subject.value;

str = str.trim();//util.js에 있는 trim함수 호출

if(!str){

alert("\n제목을 입력하세요.");//공백제거후 내용이 없으면

f.subject.focus();

return;

}

f.subject.value = str;

str = f.name.value;

str = str.trim();

if(!str){

alert("\n이름을 입력하세요.");

f.name.focus();

return;

}

f.name.value = str;

/*

//이름 한글검사

if(!isValidKorean(str)){

alert("\n이름을 정확히 입력하세요.");

f.name.focus();

return;

}

*/

if(f.email.value){

if(!isValidEmail(f.email.value)){

alert("\n정상적인 E-mail을 입력하세요");

f.email.focus();

return;

}

}

str = f.content.value;

str = str.trim();

if(!str){

alert("\n내용을 입력하세요.");

f.content.focus();

return;

}

f.content.value = str;

str = f.pwd.value;

str = str.trim();

if(!str){

alert("\n패스워드를 입력하세요.");

f.pwd.focus();

return;

}

f.pwd.value = str;

if(f.mode.value=="insert")

f.action = "<%=cp %>/bbs/created.action";

else

f.action = "<%=cp %>/bbs/updated.action";

f.submit();

}

</script>

</head>

<body>

<div id="bbs" >

<div id="bbs_title">

게 시 판(Spring 2.5)

</div>

<form action="" name="myForm" method="post">

<div id="bbsCreated">

<div class="bbsCreated_bottomLine">

<dl>

<dt>제&nbsp;&nbsp;&nbsp;&nbsp;목</dt>

<dd>

<input type="text" name="subject" size="74" value="${dto.subject }" maxlength="100" class="boxTF"/>

</dd>

</dl>

</div>

<div class="bbsCreated_bottomLine">

<dl>

<dt>작성자</dt>

<dd>

<input type="text" name="name" value="${dto.name }" size="35" maxlength="20" class="boxTF"/>

</dd>

</dl>

</div>

<div class="bbsCreated_bottomLine">

<dl>

<dt>E-Mail</dt>

<dd>

<input type="text" name="email" value="${dto.email }" size="35" maxlength="50" class="boxTF"/>

</dd>

</dl>

</div>

<div id="bbsCreated_content">

<dl>

<dt>내&nbsp;&nbsp;&nbsp;&nbsp;용</dt>

<dd>

<textarea rows="12" cols="63" name="content" class="boxTA">${dto.content }</textarea>

</dd>

</dl>

</div>

<div class="bbsCreated_noLine">

<dl>

<dt>패스워드</dt>

<dd>

<input type="password" name="pwd" value="${dto.pwd }" size="35" maxlength="7" class="boxTF"/>

&nbsp;(게시물 수정 및 삭제시 필요)

</dd>

</dl>

</div>

</div>

<div id="bbsCreated_footer">

<c:if test="${mode=='update' }">

<!-- 게시글 수정시 필요 -->

<input type="hidden" name="boardNum" value="${dto.boardNum }"/>

</c:if>

<input type="hidden" name="mode" value="${mode }"/>

<!-- 페이징 유지 -->

<input type="hidden" name="pageNum" value="${pageNum }"/>

<input type="button" value="등록하기" class="btn2"

onclick="sendIt();" />

<input type="reset" value="다시입력" class="btn2"

onclick="document.myForm.subject.focus();" />

<input type="button" value="작성취소" class="btn2"

onclick="javascript:location.href='<%=cp %>/bbs/list.action';" />

</div>

</form>

</div>

</body>

</html>

3. DTO,Controller 클래스 생성

① BoardCommand 클래스 

package com.bbs;

public class BoardCommand {//DTO

private int listNum;

//DB

private int boardNum;

private String subject;

private String name;

private String email;

private String pwd;

private String content;

private String ipAddr;

private String created;

private int hitCount;

private String mode;

private String pageNum;

Getter, Setter 작성

}

② BoardController 클래스

package com.bbs;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import com.util.MyUtil;

import com.util.dao.CommonDAO;

@Controller("bbs.boardController")

public class BoardController {

//객체 생성

@Resource(name="dao")

private CommonDAO dao;

@Resource(name="myUtil")

private MyUtil myUtil;

@RequestMapping(value="/bbs/created.action",method={RequestMethod.GET,RequestMethod.POST})

public String created(BoardCommand command,HttpServletRequest request) throws Exception{

if(command==null||command.getMode()==null||command.getMode().equals("")){

request.setAttribute("mode", "insert");

return "board/created";

}

int boardNumMax = dao.getIntValue("bbs.boardNumMax");

command.setBoardNum(boardNumMax + 1);

command.setIpAddr(request.getRemoteAddr());

dao.insertData("bbs.insertData", command);

return "redirect:/bbs/list.action";//스프링의 리다이렉트

}

}

4. iBatis 셋팅 - sqlMapConfig.xml 등록(bbs_sqlMap.xml 생성)

<?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>

<settings

cacheModelsEnabled="false"

useStatementNamespaces="true"/>

<sqlMap resource="com/util/sqlMap/temp_sqlMap.xml"/>

<sqlMap resource="com/util/sqlMap/bbs_sqlMap.xml"/>

</sqlMapConfig>

5. iBatis 셋팅 - bbs_sqlMap.xml Mapper 작성

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMap

PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="bbs">

<select id="boardNumMax" resultClass="int">

select nvl(max(boardNum),0) from sbbs

</select>

<insert id="insertData" parameterClass="com.bbs.BoardCommand">

insert into sbbs(boardNum,name,pwd,email,subject,content,ipAddr,hitCount,created)

values (#boardNum#,#name#,#pwd#,#email#,#subject#,#content#,#ipAddr#,0,sysdate)

</insert>

</sqlMap>

6. 실행 페이지


게시글 리스트 조회 기능

1. jsp 페이지 생성(View)

<%@ 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>게 시 판</title>

<link rel="stylesheet" href="<%=cp %>/board/css/style.css" type="text/css" />

<link rel="stylesheet" href="<%=cp %>/board/css/list.css" type="text/css" />

<script type="text/javascript">

function searchData(){

var f = document.searchForm;

f.action = "<%=cp%>/bbs/list.action";

f.submit();

}

</script>

</head>

<body>

<div id="bbsList">

<div id="bbsList_title">

게 시 판

</div>

<div id="bbsList_header">

<div id="leftHeader">

<form name="searchForm" method="post">

<select name="searchKey" class="selectField">

<option value="subject">제목</option>

<option value="name">작성자</option>

<option value="content">내용</option>

</select>

<input type="text" name="searchValue" class="textField"/>

<input type="button" value="검  색" class="btn2" onclick="searchData();"/>

</form>

</div>

<div id="rightHeader">

<input type="button" value=" 글올리기 " class="btn2"

onclick="javascript:location.href='<%=cp %>/bbs/created.action';"/>

</div>

</div>

<div id="bbsList_list">

<div id="title">

<dl>

<dt class="num">번호</dt>

<dt class="subject">제목</dt>

<dt class="name">작성자</dt>

<dt class="created">작성일</dt>

<dt class="hitCount">조회수</dt>

</dl>

</div>

<div id="lists">

<c:forEach var="dto" items="${lists }">

<dl>

<dd class="num">${dto.listNum}</dd>

<dd class="subject"><a href="${urlArticle }&boardNum=${dto.boardNum}">${dto.subject}</a></dd>

<dd class="name">${dto.name}</dd>

<dd class="created">${dto.created}</dd>

<dd class="hitCount">${dto.hitCount}</dd>

</dl>

</c:forEach>

</div>

<div id="footer">

<p>

<c:if test="${totalDataCount!=0 }">

${pageIndexList}

</c:if>

<c:if test="${totalDataCount==0 }">

등록된 게시물이 없습니다.

</c:if>

</p>

</div>

</div>

</div>

</body>

</html>


2. BoardController - list메소드 생성

@RequestMapping(value="/bbs/list.action",method={RequestMethod.GET,RequestMethod.POST})

public String list(HttpServletRequest request) throws Exception{

HttpSession session = request.getSession();

String cp = request.getContextPath();

int numPerPage = 10;

int totalPage = 0;

int totalDataCount = 0;

String pageNum = request.getParameter("pageNum");

//updateSubmit에서 넘어온 pageNum

if(pageNum==null)

pageNum = (String)session.getAttribute("pageNum");

session.removeAttribute("pageNum");

int currentPage = 1;

if(pageNum!=null && !pageNum.equals(""))

currentPage = Integer.parseInt(pageNum);

String searchKey = request.getParameter("searchKey");

String searchValue = request.getParameter("searchValue");

if(searchValue==null){

searchKey = "subject";

searchValue ="";

}

if(request.getMethod().equalsIgnoreCase("GET"))

searchValue = URLDecoder.decode(searchValue,"UTF-8");

Map<String,Object> hMap = new HashMap<String, Object>();

hMap.put("searchKey",searchKey);

hMap.put("searchValue", searchValue);

totalDataCount = dao.getIntValue("bbs.dataCount",hMap);

if(totalDataCount!=0)

totalPage = myUtil.getPageCount(numPerPage, totalDataCount);

if(currentPage>totalPage)

currentPage = totalPage;

int start = (currentPage-1)*numPerPage+1;

int end = currentPage*numPerPage;

hMap.put("start",start);

hMap.put("end",end);

List<Object> lists = (List<Object>)dao.getListData("bbs.listData", hMap);

int listNum,n=0;

ListIterator<Object> it = lists.listIterator();

while(it.hasNext()){

BoardCommand data = (BoardCommand)it.next();

listNum = totalDataCount - (start + n -1);

data.setListNum(listNum);

n++;

}

String params = "";

String urlList = "";

String urlArticle = "";

if(!searchValue.equals("")){

searchValue= URLEncoder.encode(searchValue,"UTF-8");

params = "searchKey=" + searchKey + "&searchValue=" +searchValue;

}

if(params.equals("")){

urlList = cp + "/bbs/list.action";

urlArticle = cp + "/bbs/article.action?pageNum="+currentPage;

}else{

urlList = cp + "/bbs/list.action" + params;

urlArticle = cp + "/bbs/article.action?pageNum="+currentPage + "&" + params;

}

request.setAttribute("lists", lists);

request.setAttribute("urlArticle", urlArticle);

request.setAttribute("pageNum", pageNum);

request.setAttribute("totalPage",totalPage);

request.setAttribute("totalDataCount",totalDataCount);

request.setAttribute("pageIndexList",myUtil.pageIndexList(currentPage, totalPage,urlList));

//리스트페이지는 항상 get방식으로 넘어오기 때문에 Post는 따로 정의안해줘도 됨

return "board/list";

}


3. bbs_sqlMap.xml Mapper 작성

<select id="dataCount" resultClass="int" parameterClass="map">

select nvl(count(*),0) from sbbs

where $searchKey$ like '%' || #searchValue# || '%'

</select>

<select id="listData" resultClass="com.bbs.BoardCommand">

select * from (

select rownum rnum, data.* from(

select boardNum,name,subject,to_char(created,'YYYY-MM-DD') created,hitCount

from sbbs

where $searchKey$ like '%' || #searchValue# || '%'

order by boardNum desc) data)

<![CDATA[

where rnum>=#start# and rnum<=#end#

]]>

</select>

 4. 실행 페이지 



게시글 조회 기능

1. bbs_sqlMap.xml : sql문 작성

<select id="readData" resultClass="com.bbs.BoardCommand" parameterClass="int">

select boardNum,name,pwd,email,subject,content,ipAddr,hitCount,created from sbbs

where boardNum=#boardNum#

</select>

<select id="preReadData" resultClass="com.bbs.BoardCommand" parameterClass="map">

<![CDATA[

select rownum, data.* from (

select boardNum,subject from sbbs

where ($searchKey$ like '%' || #searchValue# || '%')

and  (boardNum>#boardNum#) order By boardNum asc) data

where rownum=1

]]>

</select>

<select id="nextReadData" resultClass="com.bbs.BoardCommand" parameterClass="map">

<![CDATA[

select rownum, data.* from (

select boardNum,subject from sbbs

where ($searchKey$ like '%' || #searchValue# || '%')

and  (boardNum<#boardNum#) order By boardNum desc) data

where rownum=1

]]>

</select>

<update id="updateHitCount" parameterClass="int">

update sbbs set hitCount=hitCount+1

where boardNum=#boardNum#

</update>

2. BoardController - article메소드 생성(단일 게시글 조회 기능)

@RequestMapping(value="/bbs/article.action",method={RequestMethod.GET,RequestMethod.POST})

public String article(HttpServletRequest request) throws Exception{

int boardNum = Integer.parseInt(request.getParameter("boardNum"));

String pageNum = request.getParameter("pageNum");

String searchKey = request.getParameter("searchKey");

String searchValue = request.getParameter("searchValue");

if(searchValue==null){

searchKey = "subject";

searchValue = "";

}

if(request.getMethod().equalsIgnoreCase("GET")){

searchValue = URLDecoder.decode(searchValue,"UTF-8");

}

dao.updateData("bbs.updateHitCount",boardNum);

BoardCommand dto = (BoardCommand)dao.getReadData("bbs.readData", boardNum);

if(dto==null)

return "redirect:/bbsw/list.action";

int lineSu = dto.getContent().split("\r\n").length;

dto.setContent(dto.getContent().replaceAll("\r\n","<br/>"));

Map<String, Object> hMap = new HashMap<String, Object>();

hMap.put("searchKey",searchKey);

hMap.put("searchValue",searchValue);

hMap.put("boardNum",boardNum);

//이전글

BoardCommand preReadData = (BoardCommand)dao.getReadData("bbs.preReadData",hMap);

int preBoardNum = 0;

String preSubject = "";

if(preReadData!=null){

preBoardNum = preReadData.getBoardNum();

preSubject = preReadData.getSubject();

}

//다음글

BoardCommand nextReadData = (BoardCommand)dao.getReadData("bbs.nextReadData",hMap);

int nextBoardNum = 0;

String nextSubject = "";

if(nextReadData!=null){

nextBoardNum = nextReadData.getBoardNum();

nextSubject = nextReadData.getSubject();

}

String params = "pageNum="+pageNum;

if(!searchValue.equals("")){

searchValue = URLEncoder.encode(searchValue,"UTF-8");

params += "&searchKey=" + searchKey + "&searchValue=" + searchValue;

}

request.setAttribute("dto",dto);

request.setAttribute("preBoardNum", preBoardNum);

request.setAttribute("preSubject", preSubject);

request.setAttribute("nextBoardNum", nextBoardNum);

request.setAttribute("nextSubject", nextSubject);

request.setAttribute("pageNum",pageNum);

request.setAttribute("params",params);

request.setAttribute("lineSu",lineSu);

return "board/article";

}


3. JSP 페이지 생성(View)

<%@ 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>게 시 판</title>

<link rel="stylesheet" href="<%=cp %>/board/css/style.css" type="text/css" />

<link rel="stylesheet" href="<%=cp %>/board/css/article.css" type="text/css" />

<script type="text/javascript">

function deleteData(){

var boardNum = "${dto.boardNum}";

var pageNum = "${pageNum}";

var params = "?boardNum=" +boardNum + "&pageNum="+ pageNum;

var url = "<%=cp%>/bbs/deleted.action"+params;

location.replace(url);

}

function updateData(){

var boardNum = "${dto.boardNum}";

var pageNum = "${pageNum}";

var params= "?boardNum=" +boardNum + "&pageNum="+ pageNum;

var url = "<%=cp%>/bbs/updated.action"+params;

location.replace(url);

}

</script>

</head>

<body>

<div id="bbs">

<div id="bbs_title">

게 시 판(Spring2.5)

</div>

<div id="bbsArticle">

<div id="bbsArticle_header">

${dto.subject}

</div>

<div class="bbsArticle_bottomLine">

<dl>

<dt>작성자</dt>

<dd>${dto.name}<c:if test="${!empty dto.email }">

<a href="mailto:${dto.email }">(${dto.email })</a></c:if></dd>

<dt>줄수</dt>

<dd>${lineSu}</dd>

</dl>

</div>

<div class="bbsArticle_bottomLine">

<dl>

<dt>등록일</dt>

<dd>${dto.created}</dd>

<dt>조회수</dt>

<dd>${dto.hitCount}</dd>

</dl>

</div>

<div id="bbsArticle_content">

<table width="600" border="0">

<tr>

<td style="padding: 20px 80px 20px 62px;" valign="top" height="200">

${dto.content}

</td>

</tr>

</table>

</div>

<div class="bbsArticle_bottomLine">

이전글:

<c:if test="${!empty preSubject }">

<a href="<%=cp%>/bbs/article.action?${params}&boardNum=${preBoardNum}">

${preSubject}

</a>

</c:if>

</div>

<div class="bbsArticle_noLine">

다음글:

<c:if test="${!empty nextSubject }">

<a href="<%=cp%>/bbs/article.action?${params}&boardNum=${nextBoardNum}">

${nextSubject}

</a>

</c:if>

</div>

</div>

<div class="bbsArticle_noLine" style="text-align: right;">

from ${dto.ipAddr}

</div>

<div id="bbsArticle_footer">

<div id="leftFooter">

<input type="button" value=" 수정 " class="btn2" onclick="updateData();" />

<input type="button" value=" 삭제 " class="btn2" onclick="deleteData();" />

</div>

<div id="rightFooter">

<input type="button" value=" 리스트 " class="btn2"

onclick="javascript:location.href='<%=cp %>/bbs/list.action?${params }';" />

</div>

</div>

</div>

</body>

</html>

 4. 실행 페이지 


게시글 수정/삭제 기능

1. 게시글 수정/삭제 sql문 작성

<update id="updateData" parameterClass="com.bbs.BoardCommand">

update sbbs set name=#name#,pwd=#pwd#,email=#email#,

subject=#subject#,content=#content# where boardNum=#boardNum#

</update>

<delete id="deleteData" parameterClass="int">

delete sbbs where boardNum=#boardNum#

</delete>

2. 컨트롤러 작성

//수정입력

@RequestMapping(value="/bbs/updated.action",method={RequestMethod.GET})

public String updateForm(HttpServletRequest request) throws Exception{

int boardNum = Integer.parseInt(request.getParameter("boardNum"));

String pageNum = request.getParameter("pageNum");

BoardCommand dto = (BoardCommand)dao.getReadData("bbs.readData",boardNum);

if(dto==null)

return "redirect:/bbs/list.action?pageNum="+pageNum;

request.setAttribute("mode", "update");

request.setAttribute("pageNum", pageNum);

request.setAttribute("dto", dto);

return "board/created";

}

//수정반영

@RequestMapping(value="/bbs/updated.action",method={RequestMethod.POST})

public String updateSubmit(BoardCommand command, HttpServletRequest request) throws Exception{

HttpSession session = request.getSession();

dao.updateData("bbs.updateData",command);

//세션으로 페이지번호 넘김

session.setAttribute("pageNum", command.getPageNum());

return "redirect:/bbs/list.action";

//이 방식으로 전송해도 됨

//return "redirect:/bbs/list.action?pageNum="+pageNum;

}

//삭제반영

@RequestMapping(value="/bbs/deleted.action",method={RequestMethod.GET,RequestMethod.POST})

public String deleted(HttpServletRequest request) throws Exception{

HttpSession session = request.getSession();

int boardNum = Integer.parseInt(request.getParameter("boardNum"));

String pageNum = request.getParameter("pageNum");

dao.updateData("bbs.deleteData",boardNum);

//세션으로 페이지번호 넘김

session.setAttribute("pageNum", pageNum);

return "redirect:/bbs/list.action";

//이 방식으로 전송해도 됨

//return "redirect:/bbs/list.action?pageNum="+pageNum;

}

3. created.jsp에서 버튼 수정

<div id="bbsCreated_footer">

<c:if test="${mode=='update' }">

<!-- 게시글 수정시 필요 -->

<input type="hidden" name="boardNum" value="${dto.boardNum }"/>

</c:if>

<input type="hidden" name="mode" value="${mode }"/>

<!-- 페이징 유지 -->

<input type="hidden" name="pageNum" value="${pageNum }"/>

<c:if test="${mode=='insert' }">

<input type="button" value="등록하기" class="btn2"

onclick="sendIt();" />

<input type="reset" value="다시입력" class="btn2"

onclick="document.myForm.subject.focus();" />

</c:if>

<c:if test="${mode=='update' }">

<input type="button" value="수정하기" class="btn2"

onclick="sendIt();" />

</c:if>

<input type="button" value="작성취소" class="btn2"

onclick="javascript:location.href='<%=cp %>/bbs/list.action';" />

</div>


수정, 삭제 버튼 클릭시 자바스크립트를 실행하여 수정/삭제가 진행된다.

<script type="text/javascript">

function deleteData(){

var boardNum = "${dto.boardNum}";

var pageNum = "${pageNum}";

var params = "?boardNum=" +boardNum + "&pageNum="+ pageNum;

var url = "<%=cp%>/bbs/deleted.action"+params;

location.replace(url);

}

function updateData(){

var boardNum = "${dto.boardNum}";

var pageNum = "${pageNum}";

var params= "?boardNum=" +boardNum + "&pageNum="+ pageNum;

var url = "<%=cp%>/bbs/updated.action"+params;

location.replace(url);

}

</script>

 4. 실행 페이지 


'Dev > Spring' 카테고리의 다른 글

Spring2.5 - tiles  (0) 2019.04.09
Spring2.5 - 파일게시판(업로드/다운로드/삭제)  (0) 2019.04.08
Spring2.5 - Annotation  (0) 2019.04.08
Spring2.5 MVC - MultiActionController  (0) 2019.04.05
Spring2.5 MVC - AbstractWizardFormController  (0) 2019.04.05