--게시판 테이블
create table board(
idx int not null primary key AUTO_INCREMENT ,
userid VARCHAR(50) not null,
subject VARCHAR(100) not null,
content text not null,
hit int(7) DEFAULT 0 COMMENT "조회수",
post_date TIMESTAMP DEFAULT now(),
filename VARCHAR (100),
filesize LONG ,
down int default 0 COMMENT "다운로드 횟수",
ref int default 0 COMMENT "게시물 그룹 ID",
depth int default 0 COMMENT "답변 단계",
reorder int default 0 COMMENT "그룹 내에서의 순서"
);
create TRIGGER `tbl_board_update_ref`
BEFORE INSERT on board
FOR EACH ROW set new.ref =LAST_INSERT_ID() +1;
--글쓰기 (답변이 아닌 경우)
insert INTO board (idx, userid, subject, content, ref)
value(null, "braverokmc", "제목", "내용", 1);
-- 이름이 나오게 하기 위해서 member table과 조인
--
select idx, username, subject, post_date, hit, ref, depth,
reorder from board b , tbl_member m
where b.userid =m.userid
order by b.idx desc;
create or replace view board_v as
select idx, username, subject, content, post_date, hit, ref, depth, down, filename,
reorder from board b , tbl_member m
where b.userid =m.userid
order by b.idx desc;
--댓글 테이블
--comment_idx 댓글 번호
--댓글 달 게시글 번호
create table board_comment (
comment_idx int AUTO_INCREMENT primary key ,
board_idx int not null,
userid varchar(50) not null,
content text not null,
post_date Timestamp default now()
);
pom.xml 라이브러리 추가
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
SQL 에서
댓글을 위한 테이블 생성
create table board_comment (
comment_idx int AUTO_INCREMENT primary key ,
board_idx int not null,
userid varchar(50) not null,
content text not null,
post_date Timestamp default now()
);
mapper 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와 중복되지 않도록 네임스페이스 기재 -->
<mapper namespace="boardComment.Mapper">
<select id="commentList" resultType="BoardCommentDTO">
select * from board_comment where board_idx =#{board_idx} order by post_date desc
</select>
<insert id="comment_insert">
insert into board_comment ( board_idx, userid, content)
value(#{board_idx}, #{userid}, #{content})
</insert>
</mapper>
DTO 와 DAO service 를 코딩한다.
@Data
public class BoardCommentDTO {
private int comment_idx;
private int board_idx;
private String userid;
private String content;
private Date post_date;
}
@Repository
public class BoardCommentDAOImpl implements BoardCommentDAO {
@Inject
private SqlSession sqlSession;
private static final String namespace ="boardComment.Mapper";
private static final Logger logger=LoggerFactory.getLogger(BoardCommentDAOImpl.class);
@Override
public List<BoardCommentDTO> commentList(int board_idx) {
List<BoardCommentDTO> list=null;
try{
list=sqlSession.selectList(namespace+".commentList", board_idx);
}catch(Exception e){
e.printStackTrace();
}
return list;
}
@Override
public void comment_insert(BoardCommentDTO commentDTO) {
try{
sqlSession.insert(namespace+".comment_insert", commentDTO);
}catch(Exception e){
e.printStackTrace();
}
}
}
@Service
public class BoardCommentServiceImpl implements BoardCommentService {
private static final Logger logger =LoggerFactory.getLogger(BoardCommentServiceImpl.class);
@Inject
private BoardCommentDAO comentDAO ;
@Override
public List<BoardCommentDTO> commentList(int board_idx) {
// TODO Auto-generated method stub
return comentDAO.commentList(board_idx);
}
@Override
public void comment_insert(BoardCommentDTO commentDTO) {
// TODO Auto-generated method stub
comentDAO.comment_insert(commentDTO);
}
}
@RestController //spring4.0 부터 가능
@RequestMapping(value="/board")
public class CommentController {
@Inject
private BoardCommentService service;
private final Logger logger =LoggerFactory.getLogger(CommentController.class);
//댓글 등로 Ajax 로 처리
@RequestMapping(value="/comment_insert.do", method=RequestMethod.POST)
public ResponseEntity<String> comment(HttpSession session, @RequestBody BoardCommentDTO comment){
ResponseEntity<String> entity=null;
try{
logger.info("가져온 값" +comment.toString());
service.comment_insert(comment);
entity=new ResponseEntity<>("SUCCESS", HttpStatus.OK);
}catch(Exception e){
entity=new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return entity;
}
//1. @PathVariable 방식
@RequestMapping(value="/comment_list.do/{board_idx}", method=RequestMethod.GET)
public ResponseEntity<List<BoardCommentDTO>> comment_list(@PathVariable("board_idx") int board_idx){
ResponseEntity<List<BoardCommentDTO>> entity=null;
try {
List<BoardCommentDTO> commentList=service.commentList(board_idx);
logger.info(commentList.toString());
entity =new ResponseEntity<List<BoardCommentDTO>>(commentList ,HttpStatus.OK);
} catch (Exception e) {
entity =new ResponseEntity<List<BoardCommentDTO>>(HttpStatus.BAD_REQUEST);
}
return entity;
}
//2. @RequestParam 방식
@RequestMapping(value="/comment_list.do", method=RequestMethod.GET)
public @ResponseBody ResponseEntity<List<BoardCommentDTO>> comment_list2(@RequestParam int board_idx){
ResponseEntity<List<BoardCommentDTO>> entity=null;
try {
List<BoardCommentDTO> commentList=service.commentList(board_idx);
logger.info(commentList.toString());
entity =new ResponseEntity<List<BoardCommentDTO>>(commentList ,HttpStatus.OK);
} catch (Exception e) {
entity =new ResponseEntity<List<BoardCommentDTO>>(HttpStatus.BAD_REQUEST);
}
return entity;
}
//3. REST 방식 아니라 모델로 직접 데이터를 넘겨주는 방식
@RequestMapping(value="/comment_list3.do", method=RequestMethod.GET)
public List<BoardCommentDTO> comment_list3(@RequestParam int board_idx
, Model model){
List<BoardCommentDTO> commentList=null;
try {
commentList=service.commentList(board_idx);
logger.info(commentList.toString());
} catch (Exception e) {
}
return commentList;
}
}
뷰 코딩 내용
<div>
<table class="table">
<tr>
<td >
<textarea class="input-xxlarge" name="commnet_content" rows="5" cols="200" id="comment_content"></textarea>
</td>
</tr>
<tr>
<td >
<input type="button" value="댓글 달기" class="form-controll" id="btnSave">
</td>
</tr>
</table>
</div>
<hr>
<h3>댓글 목록</h3>
<div id="LplyUL" style="margin-bottom: 20px;">
</div>
Ajax 처리 방법
핸들러바를 사용해서 데이터를 보여주는 방식.
또는 자바스크립트로 직접 하드코딩 하는 방법 또는 페이지를 생성후 include 하는 방법이 있다.
먼저 핸들러바 스크립트를 작성한다.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
<script type="text/javascript">
$(document).ready(function(){
comment_list(762);
$("#btnSave").click(function(){
var comment_content =$("#comment_content").val();
var board_idx ="${view.idx}";
var userid="${loginUser.userid}";
//alert(comment_content);
$.ajax({
url : "/board/comment_insert.do",
type:"post",
/* headers:{
"Content-Type" :"application/json",
"X-HTTP-Method-Override" :"POST"
},
dataType:"text",
또는 => contentType:"application/json", 한줄 코딩
*/
contentType:"application/json",
data:JSON.stringify({
board_idx :board_idx,
userid : userid,
content :comment_content
}),
success:function(result){
if(result=="SUCCESS"){
$("#comment_content").val("");
comment_list(board_idx);
}else{
alert("등록에 실패 하였습니다.");
}
}
});
});
});
function comment_list(board_idx){
/* $.getJSON("/board/comment_list.do/"+board_idx, function(data){
printData(result, $("#LplyUL"), $("#template"));
});
또는
*/
$.ajax({
url : "/board/comment_list.do/"+board_idx,
type:"GET",
contentType:"application/json",
success:function(result){
printData(result, $("#LplyUL"), $("#template"));
}
});
}
var printData =function (replyArr, targetDiv, handleBarTemplateName){
var template =Handlebars.compile(handleBarTemplateName.html());
var html =template(replyArr);
targetDiv.html(html);
}
</script>
핸들러바 템플릿을 코딩한다.
<script id="template" type="text/x-handlebars-template">
{{#each .}}
<div class="row thumb-pad" style="color: white; border: 1px solid white; margin: 5px 0 5px 0; padding:3px;" >
<div class="span4" style="margin-bottom: 5px; margin-top:5px;">
<small class="label label-danger">{{comment_idx}}</small>
{{userid}}
</div>
<div class="span8" style="margin-bottom: 5px;">
<small class="label label-danger" style="float:right;">{{post_date}}</small>
</div>
<div class="span8" style="margin-bottom: 2px;">
<p>{{content}}</p>
<a href="#" class="btn btn-success tm_style_4" style="margin-bottom: 2px;">Read More</a>
</div>
</div>
{{/each}}
</script>
또는 직접 ajax에서 데이터를 가공한다.
~~~ 생략
success: functoin(result){
var output="<div>";
for(var i in result){
output +="";
output +=""+result[i].post_date;
output +=""+result[i].content;
output +="";
}
var output="</div>";
$("#LplyUL").html(output);
}
-- 또는
$.getJSON("/board/comment_list.do/"+board_idx+, function(data){
$(data).each(
function(){
str +="<tr><td>"
str +=""+this.content;
str +=this.post_data;
str +="</td><tr>"
});
$("#LplyUL").html(str);
});
댓글 ( 7)
댓글 남기기