댓글 기능 1

SQL 테이블 만들기

댓글 들어가기 위한 테이블 설정

기존 board 테이블의 글번호 bno를 참조해서 만듦

-- 댓글기능 넣기위한 테이블
CREATE TABLE TBL_REPLY(
    RNO     NUMBER CONSTRAINT PK_REPLY PRIMARY KEY,
    BNO     NUMBER NOT NULL, -- 게시판 테이블의 글번호
    REPLY   VARCHAR2(500)   NOT NULL, -- 댓글내용
    REPLYER VARCHAR2(100)   NOT NULL, -- 댓글작성자
    REPLYDATE DATE  DEFAULT SYSDATE,
    UPDATEDATE  DATE    DEFAULT SYSDATE,
    CONSTRAINT FK_BOARD_REPLY_BNO FOREIGN KEY (BNO) REFERENCES TBL_BOARD(BNO)
);


CREATE SEQUENCE SEQ_REPLY;

SQL 컬럼 VO 파일만들기
package com.demo.domain;

import java.util.Date;

import lombok.Data;

@Data
public class ReplyVO {

	// rno, bno, reply, replyer, replydate, updatedate
	
	private Long rno;
	private Long bno;
	private String reply;
	private String replyer;
	private Date replydate;
	private Date updatedate;
	
}

컨트롤러 생성(REST API)

@RestController을 사용한다

@Controller + @ResponseBody 리턴값을 반환

객체를 json으로 변환해서 반환

jsp파일 사용 안함

주소 : 자원을 나타내는 의미로 정의

데이터 생성 주소 : Post, 데이터 조회 주소 : Get,

데이터 삭제 주소 : Delete, 데이터 수정 주소 : Put

package com.demo.controller;

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

// 컨트롤러 클래스는 jsp파일 사용을 하지 않는다 : @RestController

@RequestMapping("/replies/*")
@RestController
public class ReplyController {

	
	
}

이후 Mapper 인터페이스, xml 파일, Service, ServiceImpl 파일까지 만든다


get.jsp 댓글 추가작업

jquery 추가

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
  <div class="row">
    <div class="col-12">
      <button type="button" id="btn_replyWrite" class="btn btn-primary">Reply Write</button>
    </div>
  </div>

  <!--댓글 목록-->
  <div class="row">
    <div class="col-12">
      <div id="replyList">

      </div>
    </div>
  </div>

<!-- footer -->
  <%@ include file="/WEB-INF/views/include/footer.jsp" %>
</div>

<!--Modal Dialog-->
<div class="modal fade" id="replyModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">New Reply</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="replyer" class="col-form-label">Replyer:</label>
            <input type="text" class="form-control" id="replyer" name="replyer">
          </div>
          <div class="form-group">
            <label for="reply" class="col-form-label">Reply:</label>
            <textarea class="form-control" id="reply" name="reply"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" id="btn_replySave" class="btn btn-primary">Save</button>
      </div>
    </div>
  </div>
</div>
<script>
      //2.댓글작업
      $(document).ready(function(){

        //댓글 모달대화상자 띄우기
        $("#btn_replyWrite").on("click", function(){
          $("#replyModal").modal('show');
        });


        //댓글저장하기
        $("#btn_replySave").on("click", function(){

          let replyer = $("#replyer").val(); //작성자
          let reply = $("#reply").val(); // 댓글내용

          //자바스크립트 Object구문
          let replyObj = { bno:${board.bno }, replyer:replyer, reply:reply };
          // 서버측에 보낼 데이타를 JSON문법구조의 문자열로 변환작업.  {"bno":5120,"replyer":"user01","reply":"댓글테스트"}
          let replyStr = JSON.stringify(replyObj);

          console.log(replyStr);

          $.ajax({
            type: 'post',
            url: '/replies/new',
            headers: {
              "Content-Type" : "application/json", "X-HTTP-Method-Override" : "POST"
            },
            dataType: 'text', // 매핑주소의 리턴값 타입
            data: replyStr, // 전송데이타 {"bno":5120,"replyer":"user01","reply":"댓글테스트"}
            success: function(result) {
              if(result == "success"){
                alert("댓글 데이타 삽입 성공");
              }
            }
          });

        });
      });
    </script>

xml 작업 -> Mapper 작업 -> Service 작업 -> ServiceImpl 작업

<insert id="insert" parameterType="com.demo.domain.ReplyVO">
		insert into TBL_REPLY(rno, bno, reply, replyer) values (SEQ_REPLY.nextval, #{bno}, #{reply}, #{replyer})
	</insert>
단, mapper.xml 에서 받아올때 반환값 int형
// mapper.xml 파일에서 insert, delete, update 구문이 실행이 반영된 데이터 행수를 리턴한다.
// 반환값 1
int insert(ReplyVO vo);
int insert(ReplyVO vo);
package com.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.domain.ReplyVO;
import com.demo.mapper.ReplyMapper;

@Service
public class ReplyServiceImpl implements ReplyService {

	@Autowired
	private ReplyMapper mapper;
	
	@Override
	public int insert(ReplyVO vo) {
		
		return mapper.insert(vo);
	}
}

컨트롤러 작업

ResponseEntity 클래스?

  1. 결과값(리턴값)
  2. 헤더
  3. HTTP상태코드
REST API
  • 리턴타입

    1. Board 클래스 : 단일데이터(단일정보). 게시물 조회 및 수정

      -> 하나의 객체일 때

      ResponseEntity 메서드명()

    2. Board 클래스 : 여러개 데이터(목록) 리스트

      -> 동일한 객체가 여러개 이상

      ResponseEntity<List> 메서드명()

    3. List, PageDTO 클래스

      -> 서로 다른 객체가 여러개 이상

      ResponseEntity<Map<String, Object» 메서드명()

@RequestMapping("/replies/*")
@RestController
@Log4j
public class ReplyController {

	@Autowired
	private ReplyService service;
	
	// 댓글 저장하기. 댓글데이터는 JSON문자열 형식으로 전송되어옴
	// {"bno":5120, "replyer":"user01", "reply":"댓글테스트"} --> ReplyVO vo
	// consumes = "application/json" : 클라이언트에서 보내는 데이터의 성격을 명시하는 구문
	// produces = {MediaType.TEXT_PLAIN_VALUE} : 서버에서 클라이언트에게 보내는 데이터의 포맷을 명시
	@PostMapping(value="/new", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE})
	public ResponseEntity<String> create(@RequestBody ReplyVO vo) {
		ResponseEntity<String> entity = null;
		
		int count = service.insert(vo);
		
		return count == 1 ? new ResponseEntity<String>("success", HttpStatus.OK)
							: new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
	}
	
	
}
ajax 추가작업 자바스크립트 추가
<script>
      //2.댓글작업
      $(document).ready(function(){

        //댓글 모달대화상자 띄우기
        $("#btn_replyWrite").on("click", function(){
          $("#replyModal").modal('show');
        });


        //댓글저장하기
        $("#btn_replySave").on("click", function(){

          let replyer = $("#replyer").val(); //작성자
          let reply = $("#reply").val(); // 댓글내용

          //자바스크립트 Object구문
          let replyObj = { bno:${board.bno }, replyer:replyer, reply:reply };
          // 서버측에 보낼 데이타를 JSON문법구조의 문자열로 변환작업.  {"bno":5120,"replyer":"user01","reply":"댓글테스트"}
          let replyStr = JSON.stringify(replyObj);

          console.log(replyStr);

          $.ajax({
            type: 'post',
            url: '/replies/new',
            headers: {
              "Content-Type" : "application/json", "X-HTTP-Method-Override" : "POST"
            },
            dataType: 'text', // 매핑주소의 리턴값 타입
            data: replyStr, // 전송데이타 {"bno":5120,"replyer":"user01","reply":"댓글테스트"}
            success: function(result) {
              if(result == "success"){
                alert("댓글 데이타 삽입 성공");
              }
            }
          });

        });
      });
    </script>

댓글남기기