-
[Spring] 게시판 만들기(15) - 게시글 등록(INSERT), 수정(UPDATE), 삭제(DELETE), 상세 조회(SELECT)Spring/4.3.x - 게시판 만들기 2018. 12. 17. 17:46반응형
게시글을 등록, 수정, 삭제, 상세 조회하는 부분을 추가하는 작업을 진행하도록 하겠습니다.
1. Back-End 파일 수정
BoardController.java, BoardService.java, BoardDao.java, BoardDto.java, BoardForm.java, BoardMapper.xml 파일을 수정하세요.
BoardController.java
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package com.spring.board.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.spring.board.dto.BoardDto;import com.spring.board.form.BoardForm;import com.spring.board.service.BoardService;@Controller@RequestMapping(value = "/board")public class BoardController {@Autowiredprivate BoardService boardService;/** 게시판 - 목록 페이지 이동 */@RequestMapping( value = "/boardList")public String boardList(HttpServletRequest request, HttpServletResponse response) throws Exception{return "board/boardList";}/** 게시판 - 목록 조회 */@RequestMapping(value = "/getBoardList")@ResponseBodypublic List<BoardDto> getBoardList(HttpServletRequest request, HttpServletResponse response, BoardForm boardForm) throws Exception {List<BoardDto> boardDtoList = boardService.getBoardList(boardForm);return boardDtoList;}/** 게시판 - 상세 페이지 이동 */@RequestMapping( value = "/boardDetail")public String boardDetail(HttpServletRequest request, HttpServletResponse response) throws Exception{return "board/boardDetail";}/** 게시판 - 상세 조회 */@RequestMapping(value = "/getBoardDetail")@ResponseBodypublic BoardDto getBoardDetail(HttpServletRequest request, HttpServletResponse response, BoardForm boardForm) throws Exception {BoardDto boardDto = boardService.getBoardDetail(boardForm);return boardDto;}/** 게시판 - 작성 페이지 이동 */@RequestMapping( value = "/boardWrite")public String boardWrite(HttpServletRequest request, HttpServletResponse response) throws Exception{return "board/boardWrite";}/** 게시판 - 등록 */@RequestMapping( value = "/insertBoard")@ResponseBodypublic BoardDto insertBoard(HttpServletRequest request, HttpServletResponse response, BoardForm boardForm) throws Exception{BoardDto boardDto = boardService.insertBoard(boardForm);return boardDto;}/** 게시판 - 삭제 */@RequestMapping( value = "/deleteBoard")@ResponseBodypublic BoardDto deleteBoard(HttpServletRequest request, HttpServletResponse response, BoardForm boardForm) throws Exception{BoardDto boardDto = boardService.deleteBoard(boardForm);return boardDto;}/** 게시판 - 수정 페이지 이동 */@RequestMapping( value = "/boardUpdate")public String boardUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception{return "board/boardUpdate";}/** 게시판 - 수정 */@RequestMapping( value = "/updateBoard")@ResponseBodypublic BoardDto updateBoard(HttpServletRequest request, HttpServletResponse response, BoardForm boardForm) throws Exception{BoardDto boardDto = boardService.updateBoard(boardForm);return boardDto;}}cs BoardService.java
더보기12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394package com.spring.board.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.spring.board.dao.BoardDao;import com.spring.board.dto.BoardDto;import com.spring.board.form.BoardForm;@Servicepublic class BoardService {@Autowiredprivate BoardDao boardDao;/** 게시판 - 목록 조회 */public List<BoardDto> getBoardList(BoardForm boardForm) throws Exception {return boardDao.getBoardList(boardForm);}/** 게시판 - 상세 조회 */public BoardDto getBoardDetail(BoardForm boardForm) throws Exception {BoardDto boardDto = new BoardDto();String searchType = boardForm.getSearch_type();if("S".equals(searchType)){int updateCnt = boardDao.updateBoardHits(boardForm);if (updateCnt > 0) {boardDto = boardDao.getBoardDetail(boardForm);}} else {boardDto = boardDao.getBoardDetail(boardForm);}return boardDto;}/** 게시판 - 등록 */public BoardDto insertBoard(BoardForm boardForm) throws Exception {BoardDto boardDto = new BoardDto();int insertCnt = boardDao.insertBoard(boardForm);if (insertCnt > 0) {boardDto.setResult("SUCCESS");} else {boardDto.setResult("FAIL");}return boardDto;}/** 게시판 - 삭제 */public BoardDto deleteBoard(BoardForm boardForm) throws Exception {BoardDto boardDto = new BoardDto();int deleteCnt = boardDao.deleteBoard(boardForm);if (deleteCnt > 0) {boardDto.setResult("SUCCESS");} else {boardDto.setResult("FAIL");}return boardDto;}/** 게시판 - 수정 */public BoardDto updateBoard(BoardForm boardForm) throws Exception {BoardDto boardDto = new BoardDto();int updateCnt = boardDao.updateBoard(boardForm);if (updateCnt > 0) {boardDto.setResult("SUCCESS");} else {boardDto.setResult("FAIL");}return boardDto;}}cs BoardDao.java
더보기12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455package com.spring.board.dao;import java.util.List;import javax.annotation.Resource;import org.apache.ibatis.session.SqlSession;import org.springframework.stereotype.Repository;import com.spring.board.dto.BoardDto;import com.spring.board.form.BoardForm;@Repositorypublic class BoardDao {@Resource(name = "sqlSession")private SqlSession sqlSession;private static final String NAMESPACE = "com.spring.board.boardMapper";/** 게시판 - 목록 조회 */public List<BoardDto> getBoardList(BoardForm boardForm) throws Exception {return sqlSession.selectList(NAMESPACE + ".getBoardList", boardForm);}/** 게시판 - 조회 수 수정 */public int updateBoardHits(BoardForm boardForm) throws Exception {return sqlSession.update(NAMESPACE + ".updateBoardHits", boardForm);}/** 게시판 - 상세 조회 */public BoardDto getBoardDetail(BoardForm boardForm) throws Exception {return sqlSession.selectOne(NAMESPACE + ".getBoardDetail", boardForm);}/** 게시판 - 등록 */public int insertBoard(BoardForm boardForm) throws Exception {return sqlSession.insert(NAMESPACE + ".insertBoard", boardForm);}/** 게시판 - 삭제 */public int deleteBoard(BoardForm boardForm) throws Exception {return sqlSession.delete(NAMESPACE + ".deleteBoard", boardForm);}/** 게시판 - 수정 */public int updateBoard(BoardForm boardForm) throws Exception {return sqlSession.update(NAMESPACE + ".updateBoard", boardForm);}}cs BoardDto.java
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133package com.spring.board.dto;public class BoardDto {int board_seq;int board_re_ref;int board_re_lev;int board_re_seq;String board_writer;String board_subject;String board_content;int board_hits;String del_yn;String ins_user_id;String ins_date;String upd_user_id;String upd_date;String result;public int getBoard_seq() {return board_seq;}public void setBoard_seq(int board_seq) {this.board_seq = board_seq;}public int getBoard_re_ref() {return board_re_ref;}public void setBoard_re_ref(int board_re_ref) {this.board_re_ref = board_re_ref;}public int getBoard_re_lev() {return board_re_lev;}public void setBoard_re_lev(int board_re_lev) {this.board_re_lev = board_re_lev;}public int getBoard_re_seq() {return board_re_seq;}public void setBoard_re_seq(int board_re_seq) {this.board_re_seq = board_re_seq;}public String getBoard_writer() {return board_writer;}public void setBoard_writer(String board_writer) {this.board_writer = board_writer;}public String getBoard_subject() {return board_subject;}public void setBoard_subject(String board_subject) {this.board_subject = board_subject;}public String getBoard_content() {return board_content;}public void setBoard_content(String board_content) {this.board_content = board_content;}public int getBoard_hits() {return board_hits;}public void setBoard_hits(int board_hits) {this.board_hits = board_hits;}public String getDel_yn() {return del_yn;}public void setDel_yn(String del_yn) {this.del_yn = del_yn;}public String getIns_user_id() {return ins_user_id;}public void setIns_user_id(String ins_user_id) {this.ins_user_id = ins_user_id;}public String getIns_date() {return ins_date;}public void setIns_date(String ins_date) {this.ins_date = ins_date;}public String getUpd_user_id() {return upd_user_id;}public void setUpd_user_id(String upd_user_id) {this.upd_user_id = upd_user_id;}public String getUpd_date() {return upd_date;}public void setUpd_date(String upd_date) {this.upd_date = upd_date;}public String getResult() {return result;}public void setResult(String result) {this.result = result;}}cs BoardForm.java
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134package com.spring.board.form;import java.util.Date;public class BoardForm {int board_seq;int board_re_ref;int board_re_lev;int board_re_seq;String board_writer;String board_subject;String board_content;int board_hits;String del_yn;String ins_user_id;Date ins_date;String upd_user_id;Date upd_date;String search_type;public int getBoard_seq() {return board_seq;}public void setBoard_seq(int board_seq) {this.board_seq = board_seq;}public int getBoard_re_ref() {return board_re_ref;}public void setBoard_re_ref(int board_re_ref) {this.board_re_ref = board_re_ref;}public int getBoard_re_lev() {return board_re_lev;}public void setBoard_re_lev(int board_re_lev) {this.board_re_lev = board_re_lev;}public int getBoard_re_seq() {return board_re_seq;}public void setBoard_re_seq(int board_re_seq) {this.board_re_seq = board_re_seq;}public String getBoard_writer() {return board_writer;}public void setBoard_writer(String board_writer) {this.board_writer = board_writer;}public String getBoard_subject() {return board_subject;}public void setBoard_subject(String board_subject) {this.board_subject = board_subject;}public String getBoard_content() {return board_content;}public void setBoard_content(String board_content) {this.board_content = board_content;}public int getBoard_hits() {return board_hits;}public void setBoard_hits(int board_hits) {this.board_hits = board_hits;}public String getDel_yn() {return del_yn;}public void setDel_yn(String del_yn) {this.del_yn = del_yn;}public String getIns_user_id() {return ins_user_id;}public void setIns_user_id(String ins_user_id) {this.ins_user_id = ins_user_id;}public Date getIns_date() {return ins_date;}public void setIns_date(Date ins_date) {this.ins_date = ins_date;}public String getUpd_user_id() {return upd_user_id;}public void setUpd_user_id(String upd_user_id) {this.upd_user_id = upd_user_id;}public Date getUpd_date() {return upd_date;}public void setUpd_date(Date upd_date) {this.upd_date = upd_date;}public String getSearch_type() {return search_type;}public void setSearch_type(String search_type) {this.search_type = search_type;}}cs BoardMapper.xml
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.spring.board.boardMapper"><select id="getBoardList" parameterType="com.spring.board.form.BoardForm" resultType="com.spring.board.dto.BoardDto">SELECT BOARD_SEQ, BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_WRITER, BOARD_SUBJECT, BOARD_CONTENT, BOARD_HITS, DEL_YN, INS_USER_ID, CAST( DATE_FORMAT( INS_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS INS_DATE, UPD_USER_ID, CAST( DATE_FORMAT( UPD_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS UPD_DATEFROM BOARD.TB_BOARDORDER BY BOARD_SEQ DESC</select><delete id="updateBoardHits" parameterType="com.spring.board.form.BoardForm">UPDATE BOARD.TB_BOARDSET BOARD_HITS = BOARD_HITS + 1, UPD_USER_ID = 'NONMEMBER', UPD_DATE = NOW()WHERE BOARD_SEQ = #{board_seq}</delete><select id="getBoardDetail" parameterType="com.spring.board.form.BoardForm" resultType="com.spring.board.dto.BoardDto">SELECT BOARD_SEQ, BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_WRITER, BOARD_SUBJECT, BOARD_CONTENT, BOARD_HITS, DEL_YN, INS_USER_ID, CAST( DATE_FORMAT( INS_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS INS_DATE, UPD_USER_ID, CAST( DATE_FORMAT( UPD_DATE, '%Y-%m-%d %H:%i:%s' ) AS CHAR(19) ) AS UPD_DATEFROM BOARD.TB_BOARDWHERE BOARD_SEQ = #{board_seq}</select><insert id="insertBoard" parameterType="com.spring.board.form.BoardForm">INSERTINTO BOARD.TB_BOARD(BOARD_RE_REF, BOARD_RE_LEV, BOARD_RE_SEQ, BOARD_WRITER, BOARD_SUBJECT, BOARD_CONTENT, INS_USER_ID, INS_DATE, UPD_USER_ID, UPD_DATE)VALUES(0, 0, 0, #{board_writer}, #{board_subject}, #{board_content}, 'NONMEMBER', NOW(), 'NONMEMBER', NOW())</insert><delete id="deleteBoard" parameterType="com.spring.board.form.BoardForm">DELETEFROM BOARD.TB_BOARDWHERE BOARD_SEQ = #{board_seq}</delete><delete id="updateBoard" parameterType="com.spring.board.form.BoardForm">UPDATE BOARD.TB_BOARDSET BOARD_SUBJECT = #{board_subject}, BOARD_CONTENT = #{board_content}, UPD_USER_ID = 'NONMEMBER', UPD_DATE = NOW()WHERE BOARD_SEQ = #{board_seq}</delete></mapper>cs 2. Front-End 파일 수정 및 추가
- boardList.jsp 파일을 수정하고 boardWrite.jsp, boardUpdate.jsp, oardDetail.jsp 파일을 추가하세요.
- Ajax를 이용하여 서버에 데이터를 요청하였고, 서버로부터 데어터를 응답받아 동적으로 구현하였습니다.boardList.jsp
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!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><!-- 공통 CSS --><link rel="stylesheet" type="text/css" href="/css/common/common.css"/><!-- 공통 JavaScript --><script type="text/javascript" src="/js/common/jquery.js"></script><script type="text/javascript">$(document).ready(function(){getBoardList();});/** 게시판 - 상세 페이지 이동 */function goBoardDetail(boardSeq){location.href = "/board/boardDetail?boardSeq="+ boardSeq;}/** 게시판 - 작성 페이지 이동 */function goBoardWrite(){location.href = "/board/boardWrite";}/** 게시판 - 목록 조회 */function getBoardList(){$.ajax({url : "/board/getBoardList",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {getBoardListCallback(obj);},error : function(xhr, status, error) {}});}/** 게시판 - 목록 조회 콜백 함수 */function getBoardListCallback(obj){var list = obj;var listLen = obj.length;var str = "";if(listLen > 0){for(var a=0; a<listLen; a++){var boardSeq = list[a].board_seq;var boardReRef = list[a].board_re_ref;var boardReLev = list[a].board_re_lev;var boardReSeq = list[a].board_re_seq;var boardWriter = list[a].board_writer;var boardSubject = list[a].board_subject;var boardContent = list[a].board_content;var boardHits = list[a].board_hits;var delYn = list[a].del_yn;var insUserId = list[a].ins_user_id;var insDate = list[a].ins_date;var updUserId = list[a].upd_user_id;var updDate = list[a].upd_date;str += "<tr>";str += "<td>"+ boardSeq +"</td>";str += "<td onclick='javascript:goBoardDetail("+ boardSeq +");' style='cursor:Pointer'>"+ boardSubject +"</td>";str += "<td>"+ boardHits +"</td>";str += "<td>"+ boardWriter +"</td>";str += "<td>"+ insDate +"</td>";str += "</tr>";}} else {str += "<tr>";str += "<td colspan='5'>등록된 글이 존재하지 않습니다.</td>";str += "<tr>";}$("#tbody").html(str);}</script></head><body><div id="wrap"><div id="container"><div class="inner"><h2>게시글 목록</h2><form id="boardForm" name="boardForm"><table width="100%" class="table01"><colgroup><col width="10%" /><col width="25%" /><col width="10%" /><col width="15%" /><col width="20%" /></colgroup><thead><tr><th>글번호</th><th>제목</th><th>조회수</th><th>작성자</th><th>작성일</th></tr></thead><tbody id="tbody"></tbody></table></form><div class="btn_right mt15"><button type="button" class="btn black mr5" onclick="javascript:goBoardWrite();">작성하기</button></div></div></div></div></body></html>cs boardWrite.jsp
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!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><!-- 공통 CSS --><link rel="stylesheet" type="text/css" href="/css/common/common.css"/><!-- 공통 JavaScript --><script type="text/javascript" src="/js/common/jquery.js"></script><script type="text/javascript">$(document).ready(function(){});/** 게시판 - 목록 페이지 이동 */function goBoardList(){location.href = "/board/boardList";}/** 게시판 - 작성 */function insertBoard(){var boardSubject = $("#board_subject").val();var boardContent = $("#board_content").val();if (boardSubject == ""){alert("제목을 입력해주세요.");$("#board_subject").focus();return;}if (boardContent == ""){alert("내용을 입력해주세요.");$("#board_content").focus();return;}var yn = confirm("게시글을 등록하시겠습니까?");if(yn){$.ajax({url : "/board/insertBoard",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {insertBoardCallback(obj);},error : function(xhr, status, error) {}});}}/** 게시판 - 작성 콜백 함수 */function insertBoardCallback(obj){if(obj != null){var result = obj.result;if(result == "SUCCESS"){alert("게시글 등록을 성공하였습니다.");goBoardList();} else {alert("게시글 등록을 실패하였습니다.");return;}}}</script></head><body><div id="wrap"><div id="container"><div class="inner"><h2>게시글 작성</h2><form id="boardForm" name="boardForm"><table width="100%" class="table02"><caption><strong><span class="t_red">*</span> 표시는 필수입력 항목입니다.</strong></caption><colgroup><col width="20%"><col width="*"></colgroup><tbody id="tbody"><tr><th>제목<span class="t_red">*</span></th><td><input id="board_subject" name="board_subject" value="" class="tbox01"/></td></tr><tr><th>작성자<span class="t_red">*</span></th><td><input id="board_writer" name="board_writer" value="" class="tbox01"/></td></tr><tr><th>내용<span class="t_red">*</span></th><td><textarea id="board_content" name="board_content" cols="10" rows="5" class="textarea01"></textarea></td></tr></tbody></table></form><div class="btn_right mt15"><button type="button" class="btn black mr5" onclick="javascript:goBoardList();">목록으로</button><button type="button" class="btn black" onclick="javascript:insertBoard();">등록하기</button></div></div></div></div></body></html>cs boardUpdate.jsp
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><!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><%String boardSeq = request.getParameter("boardSeq");%><c:set var="boardSeq" value="<%=boardSeq%>"/> <!-- 게시글 번호 --><!-- 공통 CSS --><link rel="stylesheet" type="text/css" href="/css/common/common.css"/><!-- 공통 JavaScript --><script type="text/javascript" src="/js/common/jquery.js"></script><script type="text/javascript">$(document).ready(function(){getBoardDetail();});/** 게시판 - 목록 페이지 이동 */function goBoardList(){location.href = "/board/boardList";}/** 게시판 - 상세 조회 */function getBoardDetail(boardSeq){var boardSeq = $("#board_seq").val();if(boardSeq != ""){$.ajax({url : "/board/getBoardDetail",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {getBoardDetailCallback(obj);},error : function(xhr, status, error) {}});} else {alert("오류가 발생했습니다.\n관리자에게 문의하세요.");}}/** 게시판 - 상세 조회 콜백 함수 */function getBoardDetailCallback(obj){var str = "";if(obj != null){var boardSeq = obj.board_seq;var boardReRef = obj.board_re_ref;var boardReLev = obj.board_re_lev;var boardReSeq = obj.board_re_seq;var boardWriter = obj.board_writer;var boardSubject = obj.board_subject;var boardContent = obj.board_content;var boardHits = obj.board_hits;var delYn = obj.del_yn;var insUserId = obj.ins_user_id;var insDate = obj.ins_date;var updUserId = obj.upd_user_id;var updDate = obj.upd_date;$("#board_subject").val(boardSubject);$("#board_content").val(boardContent);$("#board_writer").text(boardWriter);} else {alert("등록된 글이 존재하지 않습니다.");return;}}/** 게시판 - 수정 */function updateBoard(){var boardSubject = $("#board_subject").val();var boardContent = $("#board_content").val();if (boardSubject == ""){alert("제목을 입력해주세요.");$("#board_subject").focus();return;}if (boardContent == ""){alert("내용을 입력해주세요.");$("#board_content").focus();return;}var yn = confirm("게시글을 수정하시겠습니까?");if(yn){$.ajax({url : "/board/updateBoard",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {updateBoardCallback(obj);},error : function(xhr, status, error) {}});}}/** 게시판 - 수정 콜백 함수 */function updateBoardCallback(obj){if(obj != null){var result = obj.result;if(result == "SUCCESS"){alert("게시글 수정을 성공하였습니다.");goBoardList();} else {alert("게시글 수정을 실패하였습니다.");return;}}}</script></head><body><div id="wrap"><div id="container"><div class="inner"><h2>게시글 상세</h2><form id="boardForm" name="boardForm"><table width="100%" class="table02"><caption><strong><span class="t_red">*</span> 표시는 필수입력 항목입니다.</strong></caption><colgroup><col width="20%"><col width="*"></colgroup><tbody id="tbody"><tr><th>제목<span class="t_red">*</span></th><td><input id="board_subject" name="board_subject" value="" class="tbox01"/></td></tr><tr><th>작성자</th><td id="board_writer"></td></tr><tr><th>내용<span class="t_red">*</span></th><td colspan="3"><textarea id="board_content" name="board_content" cols="50" rows="5" class="textarea01"></textarea></td></tr></tbody></table><input type="hidden" id="board_seq" name="board_seq" value="${boardSeq}"/> <!-- 게시글 번호 --><input type="hidden" id="search_type" name="search_type" value="U"/> <!-- 조회 타입 - 상세(S)/수정(U) --></form><div class="btn_right mt15"><button type="button" class="btn black mr5" onclick="javascript:goBoardList();">목록으로</button><button type="button" class="btn black" onclick="javascript:updateBoard();">수정하기</button></div></div></div></div></body></html>cs boardDetail.jsp
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><!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><%String boardSeq = request.getParameter("boardSeq");%><c:set var="boardSeq" value="<%=boardSeq%>"/> <!-- 게시글 번호 --><!-- 공통 CSS --><link rel="stylesheet" type="text/css" href="/css/common/common.css"/><!-- 공통 JavaScript --><script type="text/javascript" src="/js/common/jquery.js"></script><script type="text/javascript">$(document).ready(function(){getBoardDetail();});/** 게시판 - 목록 페이지 이동 */function goBoardList(){location.href = "/board/boardList";}/** 게시판 - 수정 페이지 이동 */function goBoardUpdate(){var boardSeq = $("#board_seq").val();location.href = "/board/boardUpdate?boardSeq="+ boardSeq;}/** 게시판 - 상세 조회 */function getBoardDetail(boardSeq){var boardSeq = $("#board_seq").val();if(boardSeq != ""){$.ajax({url : "/board/getBoardDetail",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {getBoardDetailCallback(obj);},error : function(xhr, status, error) {}});} else {alert("오류가 발생했습니다.\n관리자에게 문의하세요.");}}/** 게시판 - 상세 조회 콜백 함수 */function getBoardDetailCallback(obj){var str = "";if(obj != null){var boardSeq = obj.board_seq;var boardReRef = obj.board_re_ref;var boardReLev = obj.board_re_lev;var boardReSeq = obj.board_re_seq;var boardWriter = obj.board_writer;var boardSubject = obj.board_subject;var boardContent = obj.board_content;var boardHits = obj.board_hits;var delYn = obj.del_yn;var insUserId = obj.ins_user_id;var insDate = obj.ins_date;var updUserId = obj.upd_user_id;var updDate = obj.upd_date;str += "<tr>";str += "<th>제목</th>";str += "<td>"+ boardSubject +"</td>";str += "<th>조회수</th>";str += "<td>"+ boardHits +"</td>";str += "</tr>";str += "<tr>";str += "<th>작성자</th>";str += "<td>"+ boardWriter +"</td>";str += "<th>작성일시</th>";str += "<td>"+ insDate +"</td>";str += "</tr>";str += "<tr>";str += "<th>내용</th>";str += "<td colspan='3'>"+ boardContent +"</td>";str += "</tr>";} else {alert("등록된 글이 존재하지 않습니다.");return;}$("#tbody").html(str);}/** 게시판 - 삭제 */function deleteBoard(){var boardSeq = $("#board_seq").val();var yn = confirm("게시글을 삭제하시겠습니까?");if(yn){$.ajax({url : "/board/deleteBoard",data : $("#boardForm").serialize(),dataType : "JSON",cache : false,async : true,type : "POST",success : function(obj) {deleteBoardCallback(obj);},error : function(xhr, status, error) {}});}}/** 게시판 - 삭제 콜백 함수 */function deleteBoardCallback(obj){if(obj != null){var result = obj.result;if(result == "SUCCESS"){alert("게시글 삭제를 성공하였습니다.");goBoardList();} else {alert("게시글 삭제를 실패하였습니다.");return;}}}</script></head><body><div id="wrap"><div id="container"><div class="inner"><h2>게시글 상세</h2><form id="boardForm" name="boardForm"><table width="100%" class="table01"><colgroup><col width="15%"><col width="35%"><col width="15%"><col width="*"></colgroup><tbody id="tbody"></tbody></table><input type="hidden" id="board_seq" name="board_seq" value="${boardSeq}"/> <!-- 게시글 번호 --><input type="hidden" id="search_type" name="search_type" value="S"/> <!-- 조회 타입 - 상세(S)/수정(U) --></form><div class="btn_right mt15"><button type="button" class="btn black mr5" onclick="javascript:goBoardList();">목록으로</button><button type="button" class="btn black mr5" onclick="javascript:goBoardUpdate();">수정하기</button><button type="button" class="btn black" onclick="javascript:deleteBoard();">삭제하기</button></div></div></div></div></body></html>cs 3. common.css와 jquery.js 파일 추가
- src/main/webapp 밑에 css/common 폴더를 생성한 후 common.css 파일을 추가하세요.- src/main/webapp 밑에 js/common 폴더를 생성한 후 jquery.js 파일을 추가하세요.
common.css
더보기123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778/* common */body,td,th{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;color:#666;letter-spacing:0px}input, button{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;overflow:visible}input[type="radio"]{*width:13px;*height:13px;font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;vertical-align:middle}input[type="checkbox"]{*width:13px;*height:13px;font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;vertical-align:middle}input[type="text"]{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;color:#666;padding-left:3px;border:1px solid #ABADB3}input[type="password"]{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;color:#666;padding-left:3px;border:1px solid #cdcdcd}input[type="file"]{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;height:22px;color:#666;background:#fff;border:1px solid #cdcdcd}select{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;color:#666;vertical-align:middle;border:none}textarea{font-family:'맑은 고딕', 'malgun', Dotum, sans-serif;font-size:12px;color:#666;padding:5px;vertical-align:middle;border:1px solid #cdcdcd}em, address{font-style:normal}/* layout */html, body{padding:0;margin:0;width:100%;height:100%;overflow:hidden;}#wrap{position:relative;width:100%;height:100%}#container{position:absolute;top:10px;right:0;bottom:38px;left:0;overflow-x:hidden;overflow-y:auto}#container .inner{width:680px; margin:0 auto; padding:10px 0}/* table */table.table01 {border-collapse:separate;border-spacing:0;text-align:center;line-height:1.5;border-top:1px solid #ccc;border-left:1px solid #ccc;margin:auto;}table.table01 th {padding: 10px;font-weight: bold;vertical-align: middle;text-align:center;border-right:1px solid #ccc;border-bottom:1px solid #ccc;border-top:1px solid #fff;border-left:1px solid #fff;background:#eee;}table.table01 td {padding:10px;vertical-align:middle;text-align:center;border-right:1px solid #ccc;border-bottom:1px solid #ccc;}table.table02 caption{height:45px;line-height:45px;color:#333;padding-left:35px;border-top:3px solid #464646;border-bottom:1px solid #c9c9c9;background:#ececec}table.table02 caption.center{padding-top:6px;height:39px;line-height:130%;text-align:center;color:#333;padding-left:0;border-top:3px solid #464646;border-bottom:1px solid #c9c9c9;background:#ececec}table.table02 tbody th{padding:10px;vertical-align:middle;font-family:'malgunbd';color:#333;border-right:1px solid #c9c9c9;border-bottom:1px solid #c9c9c9;background:#ececec}table.table02 tbody td{padding:10px;vertical-align:middle;padding-left:15px;background:#fafafa;border-bottom:1px solid #c9c9c9}/* link_style */a:link, a:visited, a:hover, a:active{color:#666;text-decoration:underline}a:hover{color:#0076c8}/* button */.btn {font-family:'malgunbd';display:inline-block;padding:3px 20px 6px 20px;margin:0;border:1px solid #aaa;cursor:pointer;color:#333;border-radius:2px;vertical-align:middle;font-size:13px;letter-spacing:-1px;line-height:normal;background-color:#feffff;text-decoration:none;}.btn.black {border-color:#191919;color:#fff;background-color:#333;text-decoration:none;}/* button_align */.btn_left{clear:both;text-align:left}.btn_right{clear:both;text-align:right}.btn_center{clear:both;text-align:center}/* select_style */.selbox{*margin-top:2px;height:28px;*height:18px;padding:3px 4px 4px 3px;border:solid 1px #abadb3;vertical-align:middle}/* textbox_style */input.tbox01{width:200px;height:26px;line-height:26px}/* textarea */textarea.textarea01{width:410px;height:95px;margin:10px 0}/* text_color_style */.t_blue{color:#004fa8}.t_red{color:#f55500}/* margin & padding */.ml5{margin-left:5px}.ml10{margin-left:10px}.ml15{margin-left:15px}.mr5{margin-right:5px}.mr15{margin-right:15px}.mr30{margin-right:30px}.mt15{margin-top:15px}.mb10{margin-bottom:10px}.mb25{margin-bottom:25px}/* page_option */.page_info{margin-bottom:10px;text-align:right}.page_info span.total_count{font-size:12px;color:#333}/* pagination */.pagination{display:block;margin-top:15px;text-align:center;line-height:normal;color:#666}.pagination *{display:inline-block;text-decoration:none;vertical-align:top}.pagination a{text-decoration:none;padding:0 5px;line-height:20px}.pagination a.onpage{font-family:'malgunbd';color:#0460a5}.pagination .direction_left01{margin:0 6px 0 3px}.pagination .direction_right01{margin:0 3px 0 6px}c jquery.js
jquery.js를 다운로드 후 추가하세요.
4. servlet-context.xml 수정
jsp에서 css, image, javascript 등 정적 자원을 사용하기 위해서 servelt-context.xml에 다음과 같이 resources를 추가하세요.
servlet-context.xml
더보기1234567891011121314151617181920212223242526272829303132333435363738394041<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --><resources mapping="/resources/**" location="/resources/" /><resources mapping="/css/**" location="/css/" /><resources mapping="/img/**" location="/img/" /><resources mapping="/js/**" location="/js/" /><!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /><beans:property name="order" value="1" /></beans:bean><context:component-scan base-package="com.spring.board" /><mvc:interceptors><mvc:interceptor><mvc:mapping path="/**"/><beans:bean id="loggerInterceptor" class="com.spring.board.common.LoggerInterceptor"></beans:bean></mvc:interceptor></mvc:interceptors><beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /></beans:beans>cs 소스 코드는 Github Repository - https://github.com/tychejin1218/board_v1 (branch : section15)를 참조하세요.
Github에서 프로젝트 가져오기 - https://tychejin.tistory.com/33반응형'Spring > 4.3.x - 게시판 만들기' 카테고리의 다른 글
[Spring] 게시판 만들기(17) - 페이징(Paging) 처리 (31) 2018.12.19 [Spring] 게시판 만들기(16) - 트랜잭션(Transaction) 설정 (11) 2018.12.19 [Spring] 게시판 만들기(14) - 게시글 조회(SELECT) (28) 2018.12.17 [Spring] 게시판 만들기(13) - mapper 및 json 설정 (3) 2018.12.14 [Spring] 게시판 만들기(12) - Mybatis 연동 (9) 2018.12.14