Spring - 웹 게시판 만들기 예제





늘은 지난번의 Spring 기반 미니 게시판에 이어 진짜 웹 게시판을 만들어 보려 합니다. 구현된 기능은 글쓰기, 글 읽기, 수정하기, 삭제하기, 댓글 달기입니다.
지난번에서 구조가 다른건 아니기 때문에 컨트롤러 쪽을 주로 보시면 이해가 되실 것 같습니다. 전 이걸 외워서 쓸 수 있을 정도가 목표입니다 -_-ㅋㅋㅋ

파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.




pack.controller 패키지

** BoardBean.java **
package pack.controller;

import java.util.Calendar;

public class BoardBean {
    private String name, pass, mail, title, cont, bip, bdate;
    private int num, readcnt, gnum, onum, nested;
    private String searchName, searchValue;  //검색용
    
    public String getSearchName() {
        return searchName;
    }
    public void setSearchName(String searchName) {
        this.searchName = searchName;
    }
    public String getSearchValue() {
        return searchValue;
    }
    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getCont() {
        return cont;
    }
    public void setCont(String cont) {
        this.cont = cont;
    }
    public String getBip() {
        return bip;
    }
    public void setBip(String bip) {
        this.bip = bip;
    }
    public String getBdate() {
        return bdate;
    }
    public void setBdate(String bdate) {
        this.bdate = bdate;
    }
    public void setBdate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        this.bdate = year + "-" + month + "-" + day;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getReadcnt() {
        return readcnt;
    }
    public void setReadcnt(int readcnt) {
        this.readcnt = readcnt;
    }
    public int getGnum() {
        return gnum;
    }
    public void setGnum(int gnum) {
        this.gnum = gnum;
    }
    public int getOnum() {
        return onum;
    }
    public void setOnum(int onum) {
        this.onum = onum;
    }
    public int getNested() {
        return nested;
    }
    public void setNested(int nested) {
        this.nested = nested;
    }
}


** DeleteController.java **
package pack.controller;

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.RequestParam;

import pack.model.BoardDaoInter;

@Controller
public class DeleteController {
    @Autowired
    private BoardDaoInter inter;
    
    @RequestMapping("delete")
    public String delPro(@RequestParam("num")String num,
        @RequestParam("page") String page) {
            if(inter.delete(num)) {
                return "redirect:/list?page=" + page;
            }else {
                return "err";
            }
        }
    }



** DetailController.java **
package pack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import pack.model.BoardDaoInter;

@Controller
public class DetailController {
    @Autowired
    private BoardDaoInter inter;
    
    @RequestMapping("detail")
    public Model detailPro(Model model, @RequestParam("num")String num,
                                                @RequestParam("page")String page) {
        //조회수 증가
        inter.updateReadcnt(num);
        
        model.addAttribute("data",inter.getDetail(num));
        model.addAttribute("page",page);
        return model;
    }
}


** EditController.java **
package pack.controller;

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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pack.model.BoardDaoInter;

@Controller
public class EditController {
    @Autowired
    private BoardDaoInter inter;
    
    @RequestMapping(value="edit", method=RequestMethod.GET)
    public ModelAndView edit(@RequestParam("num")String num,
            @RequestParam("page")String page) {
            ModelAndView view = new ModelAndView("edit", "data", inter.getDetail(num));
            view.addObject("page",page);
            return view;
    
    }
    
    @RequestMapping(value="edit", method=RequestMethod.POST)
    public ModelAndView editSubmit(@RequestParam("page")String page,
            BoardBean bean) {
        //비밀번호 체크
        String pass = inter.selectPass(Integer.toString(bean.getNum()));
        
        ModelAndView view = new ModelAndView();
        //수정
        if(bean.getPass().equals(pass)) {
            inter.update(bean);
            view.setViewName("detail"); //수정 후 상세보기
        }else {
            view.setViewName("edit");
            view.addObject("msg","비밀번호 불일치");
        }
        view.addObject("data",bean);
        view.addObject("page",page);
        return view;
        
    }
    
}


** ListController.java **
package pack.controller;



import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import pack.model.BoardDaoInter;
import pack.model.BoardDto;

@Controller
public class ListController {
    
    @Autowired
    private BoardDaoInter inter;
    
    private int tot; // 전체 레코드수
    private int plist = 5; // 페이지 당 레코드 수
    private int pageSu; //전체 페이지 수
    
    //한 화면에 보여줄 목록
    public ArrayList<BoardDto> getList(
            ArrayList<BoardDto> list, int page){
        ArrayList<BoardDto> result = new ArrayList<>();
        int start = (page -1) * plist; //0,5,10...
        int size = plist <= list.size() - start?plist:list.size() - start;
        
        for(int i = 0; i < size; i++) {
            result.add(i, list.get(start + i));
        }
        return result;
    }
    
    public int getPageSu() { // 총 페이지 수
        pageSu = tot / plist;
        if(tot % plist > 0) pageSu += 1;
        return pageSu;
        
    }

    
    @RequestMapping("list")
    public Model process(Model model, @RequestParam("page")int page) {
        tot = inter.totalCnt(); // 전체 레코드 수
        
        ArrayList<BoardDto> list = inter.getList();
        ArrayList<BoardDto> result = getList(list, page);        
        //System.out.println("result " + result.size());
        
        //model.addAttribute("data", list); paging x
        
        //paging 0
        model.addAttribute("data", result);
        model.addAttribute("pagesu", getPageSu());
        model.addAttribute("page", page);
        
        return model;
    }
}


** ReplyController.java **
package pack.controller;

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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pack.model.BoardDaoInter;

@Controller
public class ReplyController {
    @Autowired
    private BoardDaoInter inter;
    
    @RequestMapping(value="reply", method=RequestMethod.GET)
    public ModelAndView reply(@RequestParam("num")String num,
            @RequestParam("page")String page) {
        ModelAndView view =
                new ModelAndView("reply","data", inter.getDetail(num));
        view.addObject("page",page);
        return view;
    }
    @RequestMapping(value="reply", method=RequestMethod.POST)
    public String replySubmit(
            @RequestParam("page")String page, BoardBean bean) {
        bean.setOnum(bean.getOnum() + 1); //onum 갱신
        inter.updateOnum(bean);
        
        //댓글 저장
        bean.setBdate();
        bean.setNum(inter.currentNum() + 1);    // 새글 번호
        bean.setNested(bean.getNested() + 1); // 들여쓰기
        
        if(inter.insertReply(bean))
            return "redirect:/list?page=" + page;
        else
            return "err";
    }
    
}


** SearchController.java **
package pack.controller;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pack.model.BoardDaoInter;
import pack.model.BoardDto;

@Controller
public class SearchController {
    @Autowired
    private BoardDaoInter inter;
    
    @RequestMapping("search")
    public ModelAndView process(BoardBean bean) {
        ArrayList<BoardDto> list = inter.getSearch(bean);
        
        ModelAndView view = new ModelAndView("list","data",list);
        view.addObject("page", "1");
        return view;
    }
}






** WriteController.java **
package pack.controller;

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.RequestMethod;

import pack.model.BoardDaoInter;

@Controller
public class WriteController {
    @Autowired
    private BoardDaoInter inter;
    
    
    @RequestMapping(value="write", method=RequestMethod.GET)
    public String write() {
        return "writeform";
    }
    
    @RequestMapping(value="write", method=RequestMethod.POST)
    public String writeSubmit(BoardBean bean) {
        bean.setBdate(); //등록일 날짜 세팅
        int newNum = inter.currentNum() + 1; // 새글 번호
        bean.setNum(newNum); // 새글번호
        bean.setGnum(newNum); // 그룹번호
        
        if(inter.insert(bean)) {
            return "redirect:/list?page=1";
        }else {
            return "err.jsp";            
        }
    }
}




pack.model 패키지

** BoardDaoImpl.java **
package pack.model;

import java.util.ArrayList;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import pack.controller.BoardBean;

@Repository
public class BoardDaoImpl extends SqlSessionDaoSupport implements BoardDaoInter{
    @Autowired
    public BoardDaoImpl(SqlSessionFactory factory) {
        this.setSqlSessionFactory(factory);
    }
    
    public ArrayList<BoardDto> getList() {
        return (ArrayList)getSqlSession().selectList("selectList");
    }
    
    public ArrayList<BoardDto> getSearch(BoardBean bean) {
        return (ArrayList)getSqlSession().selectList("searchList", bean);
    }
    
    public boolean insert(BoardBean bean) {
        int re = getSqlSession().insert("insertData", bean);
        if (re > 0)
            return true;
        else
            return false;
    }
    
    public BoardDto getDetail(String num) {
        return getSqlSession().selectOne("selectOne", num);
    }
    
    public boolean update(BoardBean bean) {
        int re = getSqlSession().update("updateData", bean);
        if (re > 0)
            return true;
        else
            return false;
    }
    
    public boolean delete(String num) {
        int re = getSqlSession().delete("deleteData", num);
        if (re > 0)
            return true;
        else
            return false;
    }
    
    public int currentNum() {
        if(getSqlSession().selectOne("currentMaxNum") == null)
            return 0;
        
        return getSqlSession().selectOne("currentMaxNum");
    }
    
    public int totalCnt() {
        return getSqlSession().selectOne("totalCnt");
    }
    
    public boolean updateReadcnt(String num) {
        int re = getSqlSession().update("updateReadcnt", num);
        if (re > 0)
            return true;
        else
            return false;
    }
    
    public String selectPass(String num) { //수정 시 비밀번호 비교
        return getSqlSession().selectOne("selectpass", num);
    }
    
    public boolean updateOnum(BoardBean bean) {  //댓글용
        int re = getSqlSession().update("updateOnum", bean);
        if (re > 0)
            return true;
        else
            return false;
    }
    
    public boolean insertReply(BoardBean bean) { //댓글등록
        int re = getSqlSession().insert("insertReData", bean);
        if (re > 0)
            return true;
        else
            return false;
    }
}


** BoardDaoInter.java **
package pack.model;

import java.util.ArrayList;
import pack.controller.BoardBean;

public interface BoardDaoInter {
    ArrayList<BoardDto> getList();
    ArrayList<BoardDto> getSearch(BoardBean bean);
    
    boolean insert(BoardBean bean);
    BoardDto getDetail(String num);
    boolean update(BoardBean bean);
    boolean delete(String num);
    
    int currentNum();
    int totalCnt();
    boolean updateReadcnt(String num);
    String selectPass(String num);
    
    boolean updateOnum(BoardBean bean);
    boolean insertReply(BoardBean bean);
}

** BoardDto.java **
package pack.model;

public class BoardDto {
    private String name, pass, mail, title, cont, bip, bdate;
    private int num, readcnt, gnum, onum, nested;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getCont() {
        return cont;
    }
    public void setCont(String cont) {
        this.cont = cont;
    }
    public String getBip() {
        return bip;
    }
    public void setBip(String bip) {
        this.bip = bip;
    }
    public String getBdate() {
        return bdate;
    }
    public void setBdate(String bdate) {
        this.bdate = bdate;
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public int getReadcnt() {
        return readcnt;
    }
    public void setReadcnt(int readcnt) {
        this.readcnt = readcnt;
    }
    public int getGnum() {
        return gnum;
    }
    public void setGnum(int gnum) {
        this.gnum = gnum;
    }
    public int getOnum() {
        return onum;
    }
    public void setOnum(int onum) {
        this.onum = onum;
    }
    public int getNested() {
        return nested;
    }
    public void setNested(int nested) {
        this.nested = nested;
    }
}






pack.resource 패키지

** Configuration.xml **
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

<configuration>
<properties resource="pack/resource/db.properties" />
<typeAliases>
    <typeAlias type="pack.model.BoardDto" alias="dto"/>
    <typeAlias type="pack.controller.BoardBean" alias="formBean"/>
</typeAliases>
<mappers>
  <mapper resource="pack/resource/DataMapper.xml" />
</mappers>
</configuration>


** DataMapper.xml **
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

<mapper namespace="dev">
<select id="selectList" resultType="dto">
  select * from board order by gnum desc, onum asc
</select>
<select id="searchList" parameterType="formBean" resultType="dto">
  select * from board
  where ${searchName} like concat('%',#{searchValue},'%')
  order by gnum desc, onum asc
</select>
<select id="selectOne" parameterType="string" resultType="dto">
  select * from board where num=#{num}
</select>
<insert id="insertData" parameterType="formBean">
  insert into board
  values(#{num},#{name},#{pass},#{mail},#{title},
           #{cont},#{bip},#{bdate},0,#{gnum},0,0)
</insert>
<update id="updateData" parameterType="formBean">
  update board set name=#{name},mail=#{mail},
              title=#{title},cont=#{cont} where num=#{num}
</update>
<delete id="deleteData" parameterType="string">
  delete from board where num=#{num}
</delete>
<!-- 가장 큰 번호 -->
<select id="currentMaxNum" resultType="integer">
  select max(num) from board
</select>
<!-- 전체 자료 수 -->
<select id="totalCnt" resultType="integer">
  select count(*) from board
</select>
<!-- 조회수 증가 -->
<update id="updateReadcnt" parameterType="string">
  update board set readcnt = readcnt + 1 where num=#{num}
</update>
<!-- 수정 시 비밀번호 검사 -->
<select id="selectpass" parameterType="string" resultType="string">
  select pass from board where num=#{num}
</select>
<!-- 댓글용 -->
<update id="updateOnum" parameterType="formBean">
  update board set onum=onum + 1
  where onum >= #{onum} and gnum = #{gnum}
</update>
<!-- 댓글 저장 -->
<insert id="insertReData" parameterType="formBean">
  insert into board
  values(#{num},#{name},#{pass},#{mail},#{title},
           #{cont},#{bip},#{bdate},0,#{gnum},#{onum},#{nested})
</insert>
</mapper>


** db.properties **
driver=org.mariadb.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/shopdb
username=root
password=123


webapp 폴더

** detail.jsp **
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <table>
    <tr>
        <td>비밀번호 : ${data.pass}</td>
        <td>
            <a href="reply?num=${data.num}&page=${page}">
                <img src="resources/images/reply.gif">
            </a>
        </td>
        <td>
            <a href="edit?num=${data.num}&page=${page}">
                <img src="resources/images/edit.gif">
            </a>
        </td>
        <td>
            <a href="delete?num=${data.num}&page=${page}">
                <img src="resources/images/del.gif">
            </a>
        </td>
        <td>
            <a href="list?page=${page}">
                <img src="resources/images/list.gif">
            </a>
        </td>
    </tr>
    </table>
<table>
    <tr>
        <td>작성자 : ${data.name} → ${data.mail} (ip : ${data.bip})</td>
    </tr>
    <tr>
        <td>작성일 : ${data.bdate}</td>
        <td>조회수 : ${data.readcnt}</td>
    </tr>
    <tr>
        <td>제목 : ${data.title}</td>
    </tr>
    <tr>
        <td>
            <textarea rows="5" cols="30" readonly="readonly">${data.cont}</textarea>
        </td>
    </tr>
</table>    
</body>
</html>


** edit.jsp **
<%@ 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>Insert title here</title>
</head>
<body>
** 글 수정 ***<p/>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${msg !=null}">
<script type="text/javascript">
(function msg(){
    alert("${msg}")
})();
</script>
</c:if>
<form action="edit" method="post">
<input type="hidden" name="num" value="${data.num}">
<input type="hidden" name="page" value="${page}">
<table border="1">
    <tr>
        <td>작성자</td>
        <td><input type="text" name="name" value="${data.name}"></td>
    </tr>
    <tr>
        <td>암호</td>
        <td><input type="text" name="pass"></td>
    </tr>
    <tr>
        <td>이메일</td>
        <td><input type="text" name="mail" value="${data.mail}"></td>
    </tr>
    <tr>
        <td>글 제목</td>
        <td><input type="text" name="title" value="${data.title}"></td>
    </tr>
    <tr>
        <td>글 내용</td>
        <td><textarea rows="5" cols="50" name="cont">${data.cont}</textarea></td>
    </tr>
    <tr>
        <td colspan="5" style="text-align:center;">
            <input type="submit" value="수정">
            <input type="button" value="목록" onclick = "location.href='list?page=${page}'">
        </td>
    </tr>
</table>
</form>
</body>
</html>

** err.jsp **
<%@ 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>Insert title here</title>
</head>
<body>
작업 오류
<br>
<a href="list?page=1">게시 글 보기</a>
</body>
</html>

** list.jsp **
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link  rel="stylesheet" type="text/css" href="resources/css/board.css">
</head>
<body>
<h2 align="left">** 게시판(@MVC - MyBatis) **</h2>
<table>
    <Tr align="left">
            <Td>
            [<a href="list?page=1">최근목록</a>]
            [<a href="write">새글 작성</a>]
            </Td>
    </Tr>
    <tr>
        <td>
            <table border="1">
                <Tr>
                    <th>번호</th><th>글제목</th><th>작성자</th><th>작성일</th><th>조회수</th>
                </Tr>
                <c:forEach var="b" items="${data }">
                <!-- 댓글 들여쓰기 -->
                <c:set var="tab" value=""/>
                <c:forEach var="n" begin="1" end="${b.nested}">
                    <c:set var="tab" value="${tab}&nbsp;&nbsp;"/>                
                </c:forEach>                
                    <Tr>
                        <Td>${b.num }</Td>
                        <td>
                            ${tab}
                            <a href="detail?num=${b.num}&page=${page}" >${b.title }</a>
                        </td>
                        <Td>${b.name }</Td>
                        <Td>${b.bdate }</Td>
                        <td>${b.readcnt }</td>
                    </Tr>
                </c:forEach>
                <!--  paging -->
                <Tr style="text-align: center;">
                    <Td colspan="5">
                        <c:forEach var="i" begin="1" end="${pagesu }">
                            <c:if test="${i == page}">
                                <b>${i }</b>
                            </c:if>
                            <c:if test="${i != page }">
                                <a href="list?page=${i }">${i }</a>
                            </c:if>
                        </c:forEach>
                    </Td>
                </Tr>
                <!--  검색 -->
                <Tr style="text-align: center;">
                    <td colspan="5">
                            <form action="search" method="post">
                                <select name="searchName">
                                    <option value="name">작성자</option>
                                    <option value="title">글 제목</option>
                                </select> <input type="text" name="searchValue"> <input
                                    type="submit" value="검색">
                            </form>
                        </td>
                </Tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>



** reply.jsp **
<%@ 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>Insert title here</title>
</head>
<body>
* 댓글 쓰기 *<p/>
<form action="reply" method="post">
<input type="hidden" name="num" value="${data.num}">
<input type="hidden" name="page" value="${page}">
<input type="hidden" name="gnum" value="${data.gnum}">
<input type="hidden" name="onum" value="${data.onum}">
<input type="hidden" name="nested" value="${data.nested}">
<input type="hidden" name="bip" value="<%=request.getRemoteAddr()%>">

<table border="1">
    <tr>
        <td>작성자</td>
        <td><input type="text" name="name"></td>
    </tr>
    <tr>
        <td>암호</td>
        <td><input type="text" name="pass"></td>
    </tr>
    <tr>
        <td>이메일</td>
        <td><input type="text" name="mail"></td>
    </tr>
    <tr>
        <td>글 제목</td>
        <td><input type="text" name="title"></td>
    </tr>
    <tr>
        <td>글 내용</td>
        <td><textarea rows="5" cols="50" name="cont"></textarea></td>
    </tr>
    <tr>
        <td colspan="5" style="text-align:center;">
            <input type="submit" value="입력하기">
            <input type="button" value="목록" onclick = "location.href='list?page=${page}'">
        </td>
    </tr>
</table>

</form>
</body>
</html>

** writeform.jsp **
<%@ 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>Insert title here</title>
</head>
<body>
** 글 쓰기 ***<p/>
<form action="write" method="post">
<table border="1">
    <tr>
        <td>작성자</td>
        <td><input type="text" name="name"></td>
    </tr>
    <tr>
        <td>암호</td>
        <td><input type="text" name="pass"></td>
    </tr>
    <tr>
        <td>이메일</td>
        <td><input type="text" name="mail"></td>
    </tr>
    <tr>
        <td>글 제목</td>
        <td><input type="text" name="title"></td>
    </tr>
    <tr>
        <td>글 내용</td>
        <td><textarea rows="5" cols="50" name="cont"></textarea></td>
    </tr>
    <tr>
        <td colspan="5" style="text-align:center;">
            <input type="hidden" name="bip" value="<%=request.getRemoteAddr()%>">
            <input type="submit" value="입력하기">
            <input type="button" value="목록" onclick = "location.href='list?page=1'">
        </td>
    </tr>
</table>
</form>
</body>
</html>

** mvc-config.xml **
<?xml version="1.0" encoding="UTF-8"?>


    
         <context:component-scan
            base-package="pack.controller"/>
            <context:component-scan
            base-package="pack.model"/>


    <mvc:annotation-driven />
    
    <!-- mvc resource 지정 -->
    <mvc:resources location="/resources/css/" mapping="/resources/css/**"/>
    <mvc:resources location="/resources/images/" mapping="/resources/images/**"/>
    <mvc:resources location="/resources/js/" mapping="/resources/js/**"/>
    
    

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>


** web.xml **
<?xml version="1.0" encoding="ISO-8859-1"?>
  <display-name>sweb21_board_mybatis</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/application-config.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/mvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

** index.jsp **
<!DOCTYPE html>

<%@ 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="spring" uri="http://www.springframework.org/tags"%>

<html>
    <head>
        <meta charset="utf-8">
        <title>Welcome</title>
    </head>
    <body>
        <a href="list?page=1">게시판</a>
    </body>
</html>

 

그 외

** pom.xml **
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples.service.service</groupId>
    <artifactId>sweb21_board_mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>

        <!-- Generic properties -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Web -->
        <jsp.version>2.2</jsp.version>
        <jstl.version>1.2</jstl.version>
        <servlet.version>2.5</servlet.version>


        <!-- Spring -->
        <spring-framework.version>4.3.3.RELEASE</spring-framework.version>


        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

    </properties>

    <dependencies>

        <!-- Spring MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Other Web dependencies -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!--DB -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

    </dependencies>
</project>





결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.







댓글(6)

Designed by JB FACTORY