완전히 이해하려면 영상을 봐야할듯 합니다..
www.youtube.com/watch?v=9zJSkdY10oE&list=PL93mKxaRDidHvJs0PvxcZnUCrUYQZSzBT&index=30
detail.jsp
<!-- 댓글 박스 -->
<div class="row bootstrap snippets">
<div class="col-md-12">
<div class="comment-wrapper">
<div class="panel panel-info">
<div class="panel-heading m-2"><b>Comment</b></div>
<div class="panel-body">
<input type="hidden" name="userId" value="${sessionScope.principal.id}" />
<input type="hidden" name="boardId" value="${dto.id}" />
<textarea id="content" id="reply__write__form" class="form-control" placeholder="write a comment..." rows="2"></textarea>
<br>
<button onClick="replySave(${sessionScope.principal.id}, ${dto.id})" class="btn btn-primary pull-right">댓글쓰기</button>
<script>
function replySave(userId, boardId){
var data = {
userId: userId,
boardId: boardId,
content: $("#content").val()
}
$.ajax({
type: "post",
url: "/blog/reply?cmd=save",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(result){
if(result.statusCode == 1){
$("#reply__list").prepend("<div>"+data.content+"</div>")
}else{
alert("댓글쓰기 실패");
}
});
}
</script>
<div class="clearfix"></div>
<hr />
<!-- 댓글 리스트 시작-->
ajax를 사용하면 나중에 Controller에서 BufferedReader 로 읽을 수 있습니다.
ReplyDao.java
public int save(SaveReqDto dto) { // 회원가입
String sql = "INSERT INTO reply(userId, boardId, content, createDate) VALUES(?,?,?, now())";
Connection conn = DB.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
int generateKey;
try {
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, dto.getUserId());
pstmt.setInt(2, dto.getBoardId());
pstmt.setString(3, dto.getContent());
int result = pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if(rs.next()) {
generateKey = rs.getInt(1);
System.out.println("생성된 키(ID) : "+generateKey);
if(result == 1) {
return generateKey;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally { // 무조건 실행
DB.close(conn, pstmt);
}
return -1;
}
public Reply findById(int id){
String sql = "SELECT * FROM reply WHERE id = ?";
Connection conn = DB.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
// Persistence API
if(rs.next()) { // 커서를 이동하는 함수
Reply reply = new Reply();
reply.setId(rs.getInt("id"));
reply.setUserId(rs.getInt("userId"));
reply.setBoardId(rs.getInt("boardId"));
reply.setContent(rs.getString("content"));
return reply;
}
} catch (Exception e) {
e.printStackTrace();
} finally { // 무조건 실행
DB.close(conn, pstmt, rs);
}
return null;
}
sql 입니다.
SaveReqDto.java
import lombok.Data;
@Data
public class SaveReqDto {
private int userId;
private int boardId;
private String content;
}
글저장에 필요한 데이터 전송 객체
ReplyService.java
import com.cos.blog.domain.reply.ReplyDao;
import com.cos.blog.domain.reply.dto.SaveReqDto;
public class ReplyService {
private ReplyDao replyDao;
public ReplyService() {
replyDao = new ReplyDao();
}
public int 댓글쓰기(SaveReqDto dto) {
return replyDao.save(dto);
}
public Reply 댓글찾기(int id) {
return replyDao.findById(id);
}
}
ReplyController.java (서블릿)
@WebServlet("/reply")
public class ReplyController extends HttpServlet {
private static final long serialVersionUID = 1L;
public ReplyController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cmd = request.getParameter("cmd");
ReplyService replyService = new ReplyService();
// http://localhost:8080/blog/reply?cmd=save
HttpSession session = request.getSession();
if (cmd.equals("save")) {
// ajax 요청으로 얻은 data를 Buffer로 받음
BufferedReader br = request.getReader();
String reqData = br.readLine();
Gson gson = new Gson();
SaveReqDto dto = gson.fromJson(reqData, SaveReqDto.class);
System.out.println("dto : "+dto);
CommonRespDto<Reply> commonRespDto = new CommonRespDto<>();
Reply reply = null;
int result = replyService.댓글쓰기(dto);
if(result != -1) {
reply = replyService.댓글찾기(result);
commonRespDto.setStatusCode(1); //1, -1
commonRespDto.setData(reply);
}else {
commonRespDto.setStatusCode(-1); //1, -1
}
String responseData = gson.toJson(commonRespDto);
System.out.println("responseData : "+responseData);
Script.responseData(response, responseData);
}
}
}
function replySave(userId, boardId){
var data = {
userId: userId,
boardId: boardId,
content: $("#content").val()
}
$.ajax({
type: "post",
url: "/blog/reply?cmd=save",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(result){
if(result.statusCode == 1){
$("#reply__list").prepend("<div>"+data.content+"</div>")
}else{
alert("댓글쓰기 실패");
}
});
}
댓글쓰기 ajax가 호출되면 (cmd=save)
BurrferedReader br에 ajax로 요청하면서 넘기는 값 { userId: ooo, boardId: ooo, content: #("content").val() }을
String 으로 reqData 변수 에 저장합니다
reqData = " { userId: ooo, boardId: ooo, content: #("content").val() } "
방금 만든 SaveReqDto 객체에 String reqData 를 gson.fromJson( json형태의 String , 변환할 객체.class ) 을 이용해서
JSON 데이터를 JAVA Object 화 시킵니다. ( 자바코드로 써먹을수가 있다. )
if-else : setStatusCode, setData해서 commonRespDto를 만든다.
Script.responseData() 를 써서 다시 gson.toJson( Json으로 변환하고싶은 JAVA Object ) 해서 응답한다.
(JAVA Object를 JSON으로 변환 시킵니다.)
Script.java
public static void responseData(HttpServletResponse response, String jsonData) {
PrintWriter out;
try {
out = response.getWriter();
out.print(jsonData);
out.flush(); // 버퍼 비우기
} catch (IOException e) {
e.printStackTrace();
}
}
.jsp 를 응답하는게아니라 data를 응답하기위해서 만든 함수입니다.
ReplyController 에서 사용하기위해 만들었습니다.
jsonData를 받아서 그냥 그대로 다시 PrintWriter 해서 응답해줍니다.
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
detail.jsp
<script> ajax 부분을 모두 지우고, 따로 외부 js파일로 만들것입니다.
<script src="/blog/js/boardDetail.js"></script>
boardDetail.js
function addReply(data){
var replyItem = `<li id="reply-${data.id}" class="media">`;
replyItem += `<div class="media-body">`;
replyItem += `<strong class="text-primary">${data.userId}</strong>`;
replyItem += `<p>${data.content}.</p></div>`;
replyItem += `<div class="m-2">`;
replyItem += `<i onclick="deleteReply(${data.id})" class="material-icons">delete</i></div></li>`;
$("#reply__list").prepend(replyItem);
}
function deleteReply(id){
// 세션의 유저의 id와 reply의 userId를 비교해서 같을때만!!
alert("댓글 아이디 : "+id);
}
function replySave(userId, boardId) {
var data = {
userId : userId,
boardId : boardId,
content : $("#content").val()
}
$.ajax({
type : "post",
url : "/blog/reply?cmd=save",
data : JSON.stringify(data),
contentType : "application/json; charset=utf-8",
dataType : "json"
}).done(function(result) {
if (result.statusCode == 1) {
console.log(result);
addReply(result.data);
$("#content").val("");
} else {
alert("댓글쓰기 실패");
}
});
}
function deleteById(boardId){
$.ajax({
type: "post",
url: "/blog/board?cmd=delete&id="+boardId,
dataType: "json"
}).done(function(result){
console.log(result);
if(result.statusCode == 1){
location.href="index.jsp";
}else{
alert("삭제에 실패하였습니다.");
}
});
}
댓글 삭제는 아직 미구현.
댓글이 prepend 되는것을 addReply 함수로 만들어서 적용시킴.
'국비지원 Spring프레임워크 > JSP dynamic web project blog' 카테고리의 다른 글
blog 13. 댓글 삭제 (0) | 2021.03.03 |
---|---|
blog 12. 댓글 목록 보기 (0) | 2021.03.03 |
blog 10. 글 수정하기 (0) | 2021.02.26 |
blog 9. 글 삭제 ajax, 공통Dto (0) | 2021.02.23 |
blog 8. 글 상세보기 (0) | 2021.02.23 |