Continuing from 1017
create table reanswer(idx smallint auto_increment primary key,
num smallint,
nickname varchar(30),
pass varchar(20),
content varchar(2000),
writeday datetime,
foreign key(num) references reboard(num) on delete cascade);
public class AnswerDto {
private int idx;
private int num;
private String nickname;
private String pass;
private String content;
private Timestamp writeday;
//getter,setter
}
<body>
<div>
<table>
<caption align="top"><b>내용보기</b></caption>
<tr>
<td>
<h2><b>${dto.subject }</b></h2>
<span style="float: right;margin-right: 20px">
조회: ${dto.viewcount }
<fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/>
</span><br>
<h5><b>작성자: ${dto.writer }</b></h5>
</td>
</tr>
<tr>
<td>
<pre>${dto.content }</pre><br>
<!-- 이미지가 있을때만 출력 -->
<c:if test="${dto.photo!='no' }">
<c:forTokens var="p" items="${dto.photo }" delims=",">
<a href="../upload/${p }"><img src="../upload/${p }"></a>
</c:forTokens>
</c:if>
</td>
</tr>
<!-- 댓글 -->
<tr>
<td>
<div id="answer">
<b>댓글: ${acount }</b><br>
<c:forEach var="a" items="${alist }">
${a.nickname }: ${a.content }
<span>
<fmt:formatDate value="${a.writeday }" pattern="yyyy-MM-dd HH:mm"/>
<i class="bi bi-trash3-fill" style="cursor: pointer" idx="${a.idx }" num="${dto.num }"></i><br>
</span>
</c:forEach>
</div>
<form action="ainsert" method="post">
<!-- hidden -->
<input type="hidden" name="num" value="${dto.num }">
<input type="hidden" name="currentPage" value="${currentPage }">
<div class="d-inline-flex">
<b>닉네임:</b>
<input type="text" name="nickname" class="form-control" required="required">
<b>비밀번호:</b>
<input type="password" name="pass" class="form-control" required="required">
</div>
<br>
<div class="d-inline-flex">
<input type="text" name="content" class="form-control" required="required" placeholder="댓글내용을 입력해주세요">
<button type="submit">확인</button>
</div>
</form>
</td>
</tr>
<!--글쓰기,답글,수정,삭제,목록 버튼 생략-->
</table>
</div>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="answer">
<insert id="insertOfReanswer" parameterType="adto">
insert into reanswer values(null,#{num},#{nickname},#{pass},#{content},now())
</insert>
<select id="selectNumOfReanswer" resultType="adto" parameterType="int">
select * from reanswer where num=#{num} order by idx
</select>
<update id="updateViewcount" parameterType="int">
update reboard set viewcount=viewcount-1 where num=#{num}
</update>
<select id="authentificationOfAnswer" parameterType="HashMap" resultType="int">
select count(*) from reanswer where idx=#{idx} and pass=#{pass}
</select>
<delete id="deleteReanswer" parameterType="int">
delete from reanswer where idx=#{idx}
</delete>
</mapper>
@Repository
public class AnswerDao implements AnswerDaoInter{
@Autowired
private SqlSession session;
@Override
public void insertAnswer(AnswerDto dto) {
session.insert("insertOfReanswer", dto);
}
@Override
public List<AnswerDto> getAnswerList(int num) {
return session.selectList("selectNumOfReanswer", num);
}
@Override
public void controlViewcount(int num) {
session.update("answer.updateViewcount", num);
}
@Override
public int authentification(int idx, int pass) {
Map<String, Integer> map=new HashMap<String, Integer>();
map.put("idx", idx);
map.put("pass", pass);
return session.selectOne("authentificationOfAnswer", map);
}
@Override
public void deleteAnswer(int idx) {
session.delete("deleteReanswer", idx);
}
}
@Controller
public class AnswerController {
@Autowired
AnswerDaoInter adao;
@PostMapping("/board/ainsert")
public String insert(@ModelAttribute AnswerDto dto,@RequestParam int currentPage) {
adao.insertAnswer(dto);
adao.controlViewcount(dto.getNum());
return "redirect:content?num="+dto.getNum()+"¤tPage="+currentPage;
}
}
@Controller
public class BoardContentController {
@Autowired
BoardDaoInter dao;
@Autowired
AnswerDaoInter adao;
@GetMapping("/board/content")
public String content(Model model,@RequestParam int num,int currentPage) {
dao.updateViewcount(num);
BoardDto dto=dao.getData(num);
//num에 해당하는 댓글을 db에서 가져와서 보낸다
List<AnswerDto> alist=adao.getAnswerList(num);
//값이 있을때만 넘겨야 하므로
model.addAttribute("acount", alist.size());
model.addAttribute("alist", alist);
model.addAttribute("dto", dto);
model.addAttribute("currentPage", currentPage);
return "reboard/content";
}
}
<div id="answer">
<b>댓글: ${acount }</b><br>
<c:forEach var="a" items="${alist }">
${a.nickname }: ${a.content }
<span>
<fmt:formatDate value="${a.writeday }" pattern="yyyy-MM-dd HH:mm"/>
<i class="bi bi-trash3-fill" style="cursor: pointer" idx="${a.idx }" num="${dto.num }"></i><br>
</span>
</c:forEach>
</div>
<script>
$("i").on("click",function(){
var idx=$(this).attr("idx");
var num=$(this).attr("num");
var pass=prompt("비밀번호를 입력해주세요");
if(pass==null)
return;
else if(pass==""){
alert("비밀번호를 입력해주세요");
return;
}
$.ajax({
data:{"idx":idx,"pass":pass,"num":num},
type:"get",
dataType:"json",
url:"delete",
success:function(res){
if(res.no==1){
alert("삭제 완료");
location.reload();
}
else{alert("비밀번호가 틀렸습니다");}
}
});
});
</script>
@RestController
public class AnswerRestController {
@Autowired
BoardDaoInter bdao;
@Autowired
AnswerDaoInter adao;
@GetMapping("/board/delete")
public Map<String, Integer> delete(@RequestParam int idx,int pass,int num) {
int flag=adao.authentification(idx, pass);
int val=0;
if(flag!=0) {
adao.deleteAnswer(idx);
val=1;
adao.controlViewcount(num);
}
Map<String, Integer> map=new HashMap<String, Integer>();
map.put("no", val);
return map;
}
}
@Controller
public class BoardListController {
@Autowired
BoardDaoInter dao;
@Autowired
AnswerDaoInter adao;
@GetMapping("/board/list")
public String list(Model model,
@RequestParam(value = "currentPage",defaultValue = "1") int currentPage) {
//페이징처리에 필요한 변수선언
int totalCount=dao.getTotalCount();
int totalPage; //총 페이지수
int startPage; //각블럭에서 보여질 시작페이지
int endPage; //각블럭에서 보여질 끝페이지
int startNum; //db에서 가져올 글의 시작번호(mysql은 첫글이 0,오라클은 1)
int perPage=10; //한페이지당 보여질 글의 갯수
int perBlock=5; //한블럭당 보여질 페이지 개수
totalPage=totalCount/perPage+(totalCount%perPage==0?0:1);
startPage=(currentPage-1)/perBlock*perBlock+1;
endPage=startPage+perBlock-1;
if(endPage>totalPage)
endPage=totalPage;
startNum=(currentPage-1)*perPage;
//각페이지에서 필요한 게시글 가져오기
List<BoardDto> list=dao.getPagingList(startNum, perPage);
////////////////////////////////////추가부분
//list의 각글에 댓글개수 표시
for(BoardDto d:list) {
d.setAcount(adao.getAnswerList(d.getNum()).size());
}
///////////////////////////////////
//각 페이지에 출력할 시작번호
int no=totalCount-startNum;
model.addAttribute("totalCount", totalCount);
model.addAttribute("list", list); //댓글포함후 전달
model.addAttribute("startPage", startPage);
model.addAttribute("endPage", endPage);
model.addAttribute("totalPage", totalPage);
model.addAttribute("no", no);
model.addAttribute("currentPage", currentPage);
return "reboard/boardList";
}
}