[Java] 답변형 게시판 만들기(1)

1. DB 세팅

  1. 테이블 생성
create table reboard 
(num number(5) primary key, 
 writer varchar2(20), 
 subject varchar2(300),
 id varchar2(20), 
 content varchar2(1000), 
 imagename varchar2(100), 
 readcount number(5) default 0,
 groupno number(5), 
 restep number(5), 
 relevel number(5), writeday date);
  • groupno : 답글과원글을포함한글의고유번호
  • restep : 몇번째답글인지에대한숫자
  • relevel : 들여쓰기를하기위한답글레벨
  1. 시퀀스 생성
create sequence seqreboard start with 1 increment by 1 nocache;

2. 주요 로직 이해하기

  1. 원글이 추가될 때 groupno 처리
    • reboard의 총 갯수를 구하여 0개이면 groupno는 1, restep과 relevel은 0으로 db에 추가
    • 만약 글의 갯수가 0이 아니면 시퀀스 seqreboard의 next값을 groupno으로 준다.(restep. releve = 0)
  2. 답글 추가시
    • 원글로부터 groupno, restep, relevel을 전달받는다
    • groupno은 전달받은 값을 그대로 대입
    • restep은 같은 그룹중 전달받은 restep보다 크거나 같은 타 게시물의 restep은 모두 1씩 증가 후 현재 게시물의 restep은 전달받은 restep에 +1 된 값을 넣어준다
    • relevel은 무조건 전달받은 relevel에 +1 된 값을 넣어준다
  3. 출력하기
    • 1순위는 groupno의 내림차순
    • 2순위는 restep의 오름차순

3. MyBatis 세팅

  • 다음의 jar 파일이 필요 : cos, mybatis, ojdbc ,jstl, standard

  • 다음의 파일, 폴더, 메소드 를 만들어주세요

    • db.setting 패키지
      1. dbserver.properties
      2. SqlMapConfig.xml
      3. ConnectionManager.java
    • mini.board
      • BoardDto
      • BoardDao
      • BoardSql.xml
    • mini.board.servlet
      • BoardListServlet /board/list.do
      • BoardWriteServlet /board/writeform.do, /board/write.do
      • BoardUpdateServlet /board/updateform.do, /board/update.do
      • BoardDeleteServlet /board/delete.do
    • WebContent
      • board
        • boardlist.jsp
        • writeform.jsp
        • updateform.jsp
      • save

4. 세팅 테스트

​ sql

<mapper namespace="board">
  <select id="boardTotalCount" resultType="int">
    select count(*) from reboard
  </select>
</mapper>

​ DAO

public int getTotalCount()
{
  session=getSession();
  int n=session.selectOne("board.boardTotalCount");
  session.close();
  return n;
}

​ Servlet

@WebServlet("/board/list.do")
public class BoardListServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    BoardDao dao=new BoardDao();
    int totalCount=dao.getTotalCount();
    request.setAttribute("totalCount", totalCount);

    RequestDispatcher rd=request.getRequestDispatcher("boardlist.jsp");
    rd.include(request, response);
  }

  /**
			 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
			 */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

​ jsp

게시판: ${totalCount }

​ 출력결과가 아래와 같다면 성공이다

게시판: 0

5. 페이징 처리

​ sql

<select id="boardPagingList" parameterType="HashMap" resultType="bdto">
  <![CDATA[
       select a.* from (select ROWNUM as RNUM,
    b.* from (select * from reboard order by groupno desc,restep asc)b )a 
    where a.RNUM>=#{start} and a.RNUM<=#{end}
     ]]>		
</select>

​ DAO

public List<BoardDto> getList(int start,int end)
{
  Map<String, Integer> map=new HashMap<String, Integer>();
  map.put("start",start);
  map.put("end", end);

  session=getSession();
  List<BoardDto> list=session.selectList("boardPagingList",map);
  session.close();
  return list;
}

Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  BoardDao dao=new BoardDao();
  int totalCount=dao.getTotalCount();
  request.setAttribute("totalCount", totalCount);
  //코드 복사
  //페이징처리에 필요한 변수들 선언
  int currentPage; //현재 페이지
  int totalPage; //총 페이지수
  int startNum; //각페이지의시작번호
  int endNum; //각페이지의끝번호
  int startPage; //블럭의 시작페이지
  int endPage; //블럭의 끝페이지
  int no;//출력할 시작번호
  int perPage=5;//한페이지당 보여질 글의갯수
  int perBlock=5;//한블럭당 보여질 페이지의 갯수

  //총페이수를 구한다
  totalPage=totalCount/perPage+(totalCount%perPage>0?1:0);

  //현재 페이지를 읽는다(pageNum 으로 페이지를 보낼것임,없을경우도있음)
  //예) list.do?pageNum=3 , list.do
  if(request.getParameter("pageNum")==null)
    currentPage=1;
  else
    currentPage=Integer.parseInt(request.getParameter("pageNum").trim());

  //존재하지 않는 페이지일경우 마지막 페이지로 가기
  if(currentPage>totalPage)
    currentPage=totalPage;

  //각 블럭의 시작페이지와 끝페이지를 구한다
  //perBlock 이 5일경우
  //예) 현재페이지가 3 일경우 시작페이지:1,끝페이지:5
  //예) 현재페이지가 7 일경우 시작페이지:6,끝페이지:10
  //예) 현재페이지가 11 일경우 시작페이지:11,끝페이지:15
  startPage=(currentPage-1)/perBlock*perBlock+1;
  endPage=startPage+perBlock-1;
  //마지막 블럭은 끝페이지가 총 페이지수와 같아야함
  if(endPage>totalPage)
    endPage=totalPage;

  //각 페이지의 시작번호와 끝번호를 구한다
  //perPage 가 5일경우
  //예) 1페이지 : 시작번호 : 1, 끝번호:5
  //    3페이지 :           11        15
  startNum=(currentPage-1)*perPage+1;
  endNum=startNum+perPage-1;
  //마지막 페이지의 글번호 체크하기
  if(endNum>totalCount)
    endNum=totalCount;

  //각 페이지마다 출력할 시작번호
  //총갯수가 30일경우 1페이지는 30,2페이지는 25....
  no=totalCount-(currentPage-1)*perPage;		

  //2. 리스트 가져오기
  List<BoardDto> list=dao.getList(startNum, endNum);

  //3. 페이징에 필요한 변수들 request에 저장		
  request.setAttribute("list", list);
  request.setAttribute("currentPage", currentPage);
  request.setAttribute("startPage", startPage);
  request.setAttribute("endPage", endPage);
  request.setAttribute("no", no);
  request.setAttribute("totalPage", totalPage);
  request.setAttribute("totalCount", totalCount);
  ////////////////////////////
  RequestDispatcher rd=request.getRequestDispatcher("boardlist.jsp");
  rd.include(request, response);
}

​ jsp

<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Cute+Font" rel="stylesheet">

    <style type="text/css">
      div.board table{
        border: 2px solid gray;
      }
      div.board tr,div.board th,div.board td{
        border-bottom: 1px solid gray;
        border-right: 1px solid gray;
        font-size: 14pt;
        font-family: 'Cute Font';
      }
      div.board div.paging{
        font-size: 16pt;
        font-family: 'Cute Font';
        width: 630px;
        text-align: center;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <div class="board">
      <table>
        <tr bgcolor="#66cdaa">
          <th width="50">번호</th>
          <th width="350">제  목</th>
          <th width="80">작성자</th>
          <th width="100">작성일</th>
          <th width="50">조회</th>
        </tr>
        <c:if test="${totalCount==0 }">
          <tr>
            <th colspan="5">
              등록된 게시물이 없습니다
            </th>
          </tr>
        </c:if>
        <c:if test="${totalCount!=0 }">
          <c:forEach var="dto" items="${list}">
            <tr>
              <td align="center">${no }</td>
              <c:set var="no" value="${no-1 }"/>
              <td>
                <!-- 제목부분 -->
                <!-- 1 레벨당 2칸 띄기 -->
                <c:forEach var="sp" begin="1" end="${dto.relevel}">
                  &nbsp;&nbsp;
                </c:forEach>
                <!-- 답글인 경우 re 이미지 출력 -->
                <c:if test="${dto.relevel>0 }">
                  <img src="image/re.gif" width="">
                </c:if>
                <a href="#" style="color: black;">${dto.subject}</a>
              </td>
              <td align="center">${dto.writer }</td><!-- 작성자 -->
              <!-- 작성일 -->
              <td align="center">
                <fmt:formatDate value="${dto.writeday }"
                                pattern="yyyy-MM-dd"/>
              </td>
              <td align="center">${dto.readcount }</td><!-- 조회수 -->
            </tr>
          </c:forEach>
        </c:if>
      </table>
      <div class="paging">
        <!-- 이전 -->
        <c:if test="${startPage>1}">
          <a href="index.jsp?main=board/list.do?pageNum=${startPage-1}"
             style="color: black;">이전</a>
        </c:if>
        &nbsp;
        <!-- 페이지 번호 -->  
        <c:forEach var="pp" begin="${startPage}" end="${endPage}">
          <c:if test="${currentPage==pp }">
            <a href="index.jsp?main=board/list.do?pageNum=${pp}"
               style="color: red;">${pp}</a>
          </c:if>
          <c:if test="${currentPage!=pp }">
            <a href="index.jsp?main=board/list.do?pageNum=${pp}"
               style="color: black;">${pp}</a>
          </c:if>
          &nbsp;
        </c:forEach>
        <!-- 다음 -->
        <c:if test="${endPage<totalPage}">
          <a href="index.jsp?main=board/list.do?pageNum=${endPage+1}"
             style="color: black;">다음</a>
        </c:if> 

      </div> 
    </div>	
  </body>
</html>

6. 로그인 시 글쓰기 버튼 활성화

<!-- 로그인해야만 보인다 -->
<c:if test="${sessionScope.loginok!=null}">
  <a href="index.jsp?main=board/writeform.do"
     style="color: black;">
    <img src="image/btn13.gif" width="" title="글쓰기"></a>
</c:if>
<br>

7. 글쓰기 폼

​ 새 글일 경우에는 그냥 평범한 글쓰기 폼을, 답글일 경우에는 제목은 미리 세팅해준다.

​ sql

<select id="boardSelectByNum" parameterType="int" resultType="bdto">
  select * from reboard where num=#{num}
</select>

​ DAO

public BoardDto getData(int num)
{
  session=getSession();
  BoardDto dto=session.selectOne("boardSelectByNum", num);
  session.close();
  return dto;
}

​ Servlet

@WebServlet("/board/writeform.do")
public class BoardWriteServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //페이지번호,그룹번호,restep,relevel 을 읽는다
    String pageNum=request.getParameter("pageNum");
    if(pageNum==null)//페이지번호는 답글일경우에만 넘어온다
      pageNum="1";

    String num=request.getParameter("num");
    String groupno=request.getParameter("groupno");
    String restep=request.getParameter("restep");
    String relevel=request.getParameter("relevel");
    String subject="";
    //num 이나 groupno 이 널값이면 원글, 널값이 아니면 답글일경우이다
    if(num!=null)//답글인경우
    {
      int n=Integer.parseInt(num);
      BoardDao dao=new BoardDao();
      subject=dao.getData(n).getSubject();
    }else { //원글인경우
      num="0";
    }
    request.setAttribute("subject", subject);
    request.setAttribute("groupno", groupno);
    request.setAttribute("restep", restep);
    request.setAttribute("relevel", relevel);
    request.setAttribute("num", num);
    request.setAttribute("pageNum", pageNum);

    //세션으로부터 작성자,아이디를 얻어서 리퀘스트에 저장하기
    HttpSession session=request.getSession();
    String id=(String)session.getAttribute("idok");
    //아이디에 해당하는 작성자이름 얻기
    MemberDao mdao=new MemberDao();
    String writer=mdao.getName(id);

    request.setAttribute("writer", writer);
    request.setAttribute("id", id);

    RequestDispatcher rd=request.getRequestDispatcher("writeform.jsp");
    rd.include(request, response);
  }

  /**
			 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
			 */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

​ jsp - writeform

<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>     
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Cute+Font" rel="stylesheet">

    <style type="text/css">
      div.board table{
        border: 2px solid gray;
      }
      div.board tr,div.board th,div.board td{
        border-bottom: 1px solid gray;
        border-right: 1px solid gray;
        font-size: 14pt;
        font-family: 'Cute Font';
      }
    </style>
  </head>
  <body>

    <div class="board">
      <form action="board/write.do" method="post" 
            enctype="multipart/form-data">
        <table>
          <caption>글쓰기</caption>
          <tr>
            <th width="100">작성자</th>
            <td width="300">
              ${writer }(${id})
            </td>
          </tr>
          <tr>
            <th>제목</th>
            <td>
              <input type="text" name="subject" value="${subject}"
                     style="width: 250px;">
            </td> 
          </tr>
          <tr>
            <th>이미지</th>
            <td>
              <input type="file" name="upload">
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <textarea style="width: 400px;height: 150px;"
                        name="content" ></textarea>
            </td>
          </tr>
          <tr>

            <td colspan="2" align="center">
              <!-- hidden -->
              <input type="hidden" name="writer" value="${writer}"> 
              <input type="hidden" name="id" value="${id}"> 
              <input type="hidden" name="pageNum" value="${pageNum}"> 
              <c:if test="${num!=0}">
                <!-- 답글인 경우에만 보내야하는 hidden -->
                <input type="hidden" name="num" value="${num}">
                <input type="hidden" name="groupno" value="${groupno}">
                <input type="hidden" name="restep" value="${restep}">
                <input type="hidden" name="relevel" value="${relevel}">
              </c:if>

              <button type="submit">게시글저장</button>
              <button type="button" 
                      onclick="location.href='index.jsp?main=board/list.do?pageNum=${pageNum}'">목록가기</button>
            </td>
          </tr>
        </table>	
      </form>
    </div>
  </body>
</html>

8. 글 저장 - 새 글, 답글

​ sql

<update id="boardUpdateRestep" parameterType="HashMap">
  <![CDATA[
     update reboard set restep=restep+1
      where groupno=#{groupno} and restep>#{restep}
    ]]>		
</update>

<insert id="boardInsert" parameterType="bdto">
  insert into reboard values (seqreboard.nextval,#{writer},
  #{id},#{subject},#{content},#{imagename},0,#{groupno},
  #{restep},#{relevel},sysdate)
</insert>

<select id="boardMaxNum" resultType="int">
  select max(num) from reboard
</select>

​ DAO

public void updateRestep(int groupno,int restep)
{
  Map<String, Integer>map=new HashMap<String, Integer>();
  map.put("groupno",groupno);
  map.put("restep",restep);
  session=getSession();
  session.update("boardUpdateRestep",map);
  session.close();		
}

//그룹넘버를 구하기 위해서 필요함
public int getMaxNum()
{
  session=getSession();
  int max=session.selectOne("boardMaxNum");
  session.close();
  return max;				
}

public void boardInsert(BoardDto dto)
{
  int groupno=dto.getGroupno();
  int restep=dto.getRestep();
  int relevel=dto.getRelevel();
  int num=dto.getNum();

  //답글인경우
  if(num!=0)
  {
    //같은 그룹중 전달받은 restep 보다 큰값은 1증가
    updateRestep(groupno, restep);
    //현재 저장할 데이타의 restep,relevel 을 1증가
    restep++;
    relevel++;
  }else {//새글인경우
    //현재 게시글이 없으면 그룹번호는 1로
    //있을경우에는 num 의 최대값+1 로 주기로 한다
    if(getTotalCount()==0)
      groupno=1;
    else
      groupno=getMaxNum()+1;

    //원글은 restep,relevel 은 0 으로 저장함
    restep=0;
    relevel=0;
  }
  //새로 구한값들을(새글,답글 모두) dto 에 담는다
  dto.setGroupno(groupno);
  dto.setRestep(restep);
  dto.setRelevel(relevel);

  //insert 실행
  session=getSession();
  session.insert("boardInsert",dto);
  session.close();				
}

​ Servlet

@WebServlet("/board/write.do")
public class BoardInsertServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    BoardDao dao=new BoardDao();
    BoardDto dto=new BoardDto();
    //실제 파일이 업로드될 경로
    String realPath=request.getSession().getServletContext().getRealPath("/save");
    System.out.println("realPath:"+realPath);
    MultipartRequest multi=null;
    try {
      multi=new MultipartRequest(request,
                                 realPath,1024*1024*2,"UTF-8",new DefaultFileRenamePolicy());
      //입력자료 읽기
      int num,groupno,restep,relevel;
      try {
        num=Integer.parseInt(multi.getParameter("num"));
        groupno=Integer.parseInt(multi.getParameter("groupno"));
        restep=Integer.parseInt(multi.getParameter("restep"));
        relevel=Integer.parseInt(multi.getParameter("relevel"));
      }catch(NumberFormatException e) {
        num=groupno=restep=relevel=0;
      }
      String subject=multi.getParameter("subject");
      String content=multi.getParameter("content");
      String imagename=multi.getFilesystemName("upload");
      String writer=multi.getParameter("writer");
      String id=multi.getParameter("id");

      //dto 에 담기
      dto.setNum(num);
      dto.setWriter(writer);
      dto.setId(id);
      dto.setSubject(subject);
      dto.setContent(content);
      dto.setGroupno(groupno);
      dto.setRestep(restep);
      dto.setRelevel(relevel);
      dto.setImagename(imagename==null?"noimg":imagename);
      //insert
      dao.boardInsert(dto);

      //일단은 목록으로 이동-나중에 
      //content 완성후에는 content 이동으로 수정
      String pageNum=multi.getParameter("pageNum");
      response.sendRedirect("../index.jsp?main=board/list.do?pageNum="+pageNum);	

    }catch(Exception e) {
      System.out.println("파일 업로드 오류:"+e.getMessage());
    }		
  }

  /**
		 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
		 */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

9. 내용 조회

​ 조회수 카운트를 올린다

​ sql

<update id="boardUpdateReadcount" parameterType="int">
  update reboard set readcount=readcount+1 where num=#{num}
</update>

​ DAO

public void updateReadcount(int num)
{
  session=getSession();
  session.update("boardUpdateReadcount", num);
  session.close();		
}

​ Servlet

@WebServlet("/board/content.do")
public class BoardContentServlet extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    int num=Integer.parseInt(request.getParameter("num"));
    String pageNum=request.getParameter("pageNum");
    //조회수 증가
    BoardDao dao=new BoardDao();
    dao.updateReadcount(num);

    //dto 데이타 가져오기
    BoardDto dto=dao.getData(num);

    //request 에 저장
    request.setAttribute("dto", dto);
    request.setAttribute("pageNum", pageNum);

    //include
    RequestDispatcher rd=request.getRequestDispatcher("content.jsp");
    rd.include(request, response);
  }

  /**
		 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
		 */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}

​ jsp

<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>     
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Cute+Font" rel="stylesheet">

    <style type="text/css">
      div.board table{
        border: 2px solid gray;
      }
      div.board tr,div.board th,div.board td{
        border-bottom: 1px solid gray;
        border-right: 1px solid gray;
        font-size: 14pt;
        font-family: 'Cute Font';
      }
      div.board td pre
      {
        font-size: 14pt;
        font-family: 'Cute Font';
      }
    </style>
  </head>
  <body>
    <div class="board">
      <table>
        <caption><b>내용보기</b></caption>
        <tr>
          <td width="500">
            <b style="padding-left: 20px;">${dto.subject}</b>
          </td>
        </tr>
        <tr height="200" >
          <td>
            <span style="color: gray;">${dto.writer}(${dto.id})</span>
            <span style="margin-left: 270px;color: gray;">
              <fmt:formatDate value="${dto.writeday}"
                              pattern="yyyy-MM-dd HH:mm"/></span>
            <br><br>
            <!-- 이미지 출력 -->
            <c:if test="${dto.imagename!='noimg'}">
              <img src="save/${dto.imagename}"
                   style="max-width: 400px;">
              <br>				  
            </c:if>
            <!-- 내용 출력 -->
            <pre>${dto.content}</pre>	
          </td>
        </tr>
        <tr>
          <td>
            <span style="margin-left: 20px;color: gray;">
              조회 ${dto.readcount}</span>
            <br>
            <span style="margin-left: 200px;">
              <!-- 답글,수정,삭제는 로그인한 사람만 보이도록 하기 -->
              <c:if test="${sessionScope.loginok!=null}">
                <button type="button" 
                        onclick="location.href='index.jsp?main=board/writeform.do?num=${dto.num}&groupno=${dto.groupno}&restep=${dto.restep}&relevel=${dto.relevel}&pageNum=${pageNum}'"
                        style="width: 80px;color: blue;">답글</button>	
                <!-- 수정,삭제는 본인한테만 보이도록 하기 -->				
                <c:if test="${dto.id==sessionScope.idok}">
                  <button type="button" 
                          onclick=""
                          style="width: 80px;color: #008b8b;">수정</button>
                  <button type="button" 
                          onclick=""
                          style="width: 80px;color: #2e8b57;">삭제</button>
                </c:if>	
              </c:if>	
              <button type="button" 
                      onclick=""
                      style="width: 80px;color: magenta;">목록</button>
            </span>
          </td>
        </tr>
      </table>
    </div>
  </body>
</html>

10. 댓글 달기

  1. 새로운 테이블 추가 : BoardAnswer

  2. DTO

public class BoardAnswerDto {
	private int seq;
	private int num;
	private String writer;
	private String id;
	private String content;
	private Timestamp writeday;

	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Timestamp getWriteday() {
		return writeday;
	}
	public void setWriteday(Timestamp writeday) {
		this.writeday = writeday;
	}
}
  1. DAO

    	public class BoardAnswerDao {
    		ConnectionManager conn=ConnectionManager.getInstance();
    		SqlSession session;
       	
    		private SqlSession getSession()
    		{
    			session=conn.openSession();
    			return session;
    		}
    	}
    
  2. Sql

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="boardanswer">
       
    </mapper>
    
  3. SqlMapConfig.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
      <properties resource="db/setting/dbserver.properties"/>
      <typeAliases>
        <typeAlias type="mini.board.data.BoardDto" alias="bdto"/>
        <typeAlias type="mini.board.data.BoardAnswerDto" alias="badto"/>
      </typeAliases>
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
          <dataSource type="POOLED">
            <property name="driver" value="${DRIVER}"/>
            <property name="url" value="${URL}"/>
            <property name="username" value="${USERNAME}"/>
            <property name="password" value="${PASSWORD}"/>
          </dataSource>
        </environment>
      </environments>
      <mappers>
        <mapper resource="mini/board/data/BoardSql.xml"/>
        <mapper resource="mini/board/data/BoardAnswerSql.xml"/>
      </mappers>
    </configuration>
    
  4. 댓글 폼 작성

    //로그인한 사람의 아이디랑 이름 얻기
    HttpSession session=request.getSession();
    String id=(String)session.getAttribute("idok");
    MemberDao mdao=new MemberDao();
    String writer=mdao.getName(id);
       
    request.setAttribute("id", id);
    request.setAttribute("writer", writer);
       
    content.jsp 에 코드 추가
    : 조회 출력 아래쪽
    <br>
    <!-- 로그인한 경우에만 보이는 댓글폼 -->
    <c:if test="${sessionScope.loginok!=null }">
      <form action="#" method="post">
        <textarea style="width: 370px; height: 70px;"
                  name="content"></textarea>
        <button type="submit"
                style="position: relative;width: 100px;height: 80px;top: -30px;">등록</button>
        <!-- hidden 4개-->
        <input type="hidden" name="num" value="${dto.num}">
        <input type="hidden" name="pageNum" value="${pageNum}">
        <input type="hidden" name="writer" value="${writer}">
        <input type="hidden" name="id" value="${id}">
       
      </form>					
    </c:if>
       
    

Categories:

Updated:

Comments