JSP
- 댓글의 작성자는 로그인 한 아이디, 제목은 원글에 --> 붙여서, parent는 원글 번호. (원글은 0)
- 화면에는 내용 입력 창과 작성 버튼만 띄움. (작성자, 제목, parent는 DB 저장용 데이터니까)
<form name = "repf">
댓글: <input type="text" name="content">
<input type ="hidden" name = "writer" value="${sessionScope.loginId}">
<input type ="hidden" name = "title" value="-->${vo.title}">
<input type ="hidden" name = "parent" value="${vo.num}">
<input type ="button" value="작성" onclick="a()">
</form>
- 상세페이지를 열자마자 해당 원글의 댓글을 전부 볼 수 있도록 forEach 문으로 값을 불러옴.
<div id = "reps">
<c:forEach var="rep" items="${reps}">
${rep.content} (writer:${rep.writer}) <br/>
</c:forEach>
</div>
- 댓글 작성 버튼을 누르면 a() 함수 호출.
- 폼 값을 전부 파라메터에 넣고 post 방식으로 add.java로 이동함.
- 서버에서 준 값을 파싱해서 for-of 문으로 배열 값을 String에 넣어 원하는 위치에 넣음.
- 댓글 입력창을 초기화해줌
let div = document.getElementById("reps");
div.innerHTML = html;
repf.content.value = '';
전체코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function a(){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let arr = JSON.parse(xhttp.responseText);
html = '';
for(let obj of arr){ /* 자바스크립트의 반복자 */
html += obj.content+" (writer: "+obj.writer+")<br/>";
}
let div = document.getElementById("reps");
div.innerHTML = html;
repf.content.value = '';
}
let param = "writer=" + repf.writer.value;
param += "&title=" + repf.title.value;
param += "&parent=" + repf.parent.value;
param += "&content=" + repf.content.value;
xhttp.open("POST", "${pageContext.request.contextPath}/board/add");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
</script>
</head>
<body>
<c:if test="${sessionScope.loginId!=vo.writer}">
<c:set var="str">readonly</c:set>
</c:if>
<h3>글 상세페이지</h3>
<a href="${pageContext.request.contextPath}/board/list">글목록</a><br/>
<form action="${pageContext.request.contextPath}/board/detail" method="post">
<table border = "1">
<tr><th>글번호</th><td><input type="number" name="num" value="${vo.num}" readonly></td></tr>
<tr><th>작성자</th><td><input type="text" value="${vo.writer}" readonly></td></tr>
<tr><th>작성일자</th><td><input type="date" value="${vo.w_date}" readonly></td></tr>
<tr><th>제목</th><td><input type="text" name="title" value="${vo.title}" ${str}></td></tr>
<tr><th>내용</th><td><textarea name = "content" row="10" cols="30" ${str}>${vo.content}</textarea></td></tr>
<c:if test="${sessionScope.loginId==vo.writer}">
<tr><th>수정/삭제</th><td>
<input type="submit" value="수정">
<input type="button" value="삭제" onclick="location.href = '${pageContext.request.contextPath}/board/del?num=${vo.num}'">
</td></tr>
</c:if>
<tr>
<th>댓글작성</th>
<td>
<form name = "repf">
댓글: <input type="text" name="content">
<input type ="hidden" name = "writer" value="${sessionScope.loginId}">
<input type ="hidden" name = "title" value="-->${vo.title}">
<input type ="hidden" name = "parent" value="${vo.num}">
<input type ="button" value="작성" onclick="a()">
</form>
<div id = "reps">
<c:forEach var="rep" items="${reps}">
${rep.content} (writer:${rep.writer}) <br/>
</c:forEach>
</div>
</td>
</tr>
</table>
</body>
</html>
Servlet
- 폼파라메터값을 읽어와서 Service의 add 메소드로 db 입력.
- 원글 번호로 select. JSON 객체에 필요한 값을 담고 배열로 감싸기.
- JSON을 문자열로 변환해 JSP에 전달.
ArrayList<ImgRepVo> reps = service.getReps(pnum); //원글 번호로 원글에 달린 댓글 전부 불러오기
JSONArray arr = new JSONArray(); //[배열]
for (ImgRepVo vo:reps) {
JSONObject obj = new JSONObject(); //{객체}
obj.put("writer", vo.getWriter());
obj.put("content", vo.getContent());
arr.add(obj);
}
String txt = arr.toJSONString();
response.getWriter().append(txt);
전체 코드
package imgreps.controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import imgreps.ImgRepService;
import imgreps.ImgRepVo;
/**
* Servlet implementation class ImgRepAdd
*/
@WebServlet("/imgrep/add")
public class ImgRepAdd extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ImgRepAdd() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
int pnum = Integer.parseInt(request.getParameter("pnum")); //원글번호
String writer = request.getParameter("writer");
String content = request.getParameter("content");
ImgRepService service = new ImgRepService();
service.addRep(new ImgRepVo(0, pnum, writer, content));
ArrayList<ImgRepVo> reps = service.getReps(pnum); //원글 번호로 원글에 달린 댓글 전부 불러오기
JSONArray arr = new JSONArray();
for (ImgRepVo vo:reps) {
JSONObject obj = new JSONObject();
obj.put("writer", vo.getWriter());
obj.put("content", vo.getContent());
arr.add(obj);
}
String txt = arr.toJSONString();
response.getWriter().append(txt);
}
/**
* @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);
}
}