목차 | |
1. | comment |
1. comment
▣ CommentVO.java
package com.ezen.spring.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CommentVO {
private long cno;
private long bno;
private String writer;
private String content;
private String regDate;
}
▣ CommentController.java
package com.ezen.spring.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.ezen.spring.domain.CommentVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.PagingHandler;
import com.ezen.spring.service.CommentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/comment/*")
@RestController
public class CommentController {
private final CommentService csv;
@PostMapping("/post")
public ResponseEntity<String> post(@RequestBody CommentVO cvo) {
log.info(">>>> post cvo > {}", cvo);
int isOk = csv.post(cvo);
return isOk > 0 ?
new ResponseEntity<String>("1",HttpStatus.OK) :
new ResponseEntity<String>("0", HttpStatus.INTERNAL_SERVER_ERROR); //error
}
@GetMapping(value="/{bno}/{page}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<CommentVO>> list(@PathVariable("bno") long bno){
List<CommentVO> list = csv.getList(bno);
return new ResponseEntity<List<CommentVO>>(list, HttpStatus.OK);
}
// @GetMapping(value="/{bno}/{page}", produces = MediaType.APPLICATION_JSON_VALUE)
// public ResponseEntity<PagingHandler> list(@PathVariable("bno") long bno, @PathVariable("page") int page){
// PagingVO pgvo = new PagingVO(page, 5);
// PagingHandler ph = csv.getList(bno, pgvo);
// return new ResponseEntity<PagingHandler>(ph, HttpStatus.OK);
// }
// @PutMapping("/modify")
// public ResponseEntity<String> update(@RequestBody CommentVO cvo){
//
// }
@ResponseBody
@PutMapping("/modify")
public String modify(@RequestBody CommentVO cvo) {
int isOk = csv.modify(cvo);
return isOk > 0 ? "1" : "0";
}
@ResponseBody
@DeleteMapping("/{cno}")
public String delete(@PathVariable("cno") long cno) {
int isOk = csv.delete(cno);
return isOk > 0 ? "1" : "0";
}
}
▣ CommentService.java
package com.ezen.spring.service;
import java.util.List;
import com.ezen.spring.domain.CommentVO;
import com.ezen.spring.domain.PagingVO;
import com.ezen.spring.handler.PagingHandler;
public interface CommentService {
int post(CommentVO cvo);
List<CommentVO> getList(long bno);
int modify(CommentVO cvo);
int delete(long cno);
// PagingHandler getList(long bno, PagingVO pgvo);
}
▣ CommentServiceImpl.java
package com.ezen.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ezen.spring.dao.CommentDAO;
import com.ezen.spring.domain.CommentVO;
//import com.ezen.spring.domain.PagingVO;
//import com.ezen.spring.handler.PagingHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor
@Slf4j
@Service
public class CommentServiceImpl implements CommentService{
private final CommentDAO cdao;
@Override
public int post(CommentVO cvo) {
// TODO Auto-generated method stub
return cdao.post(cvo);
}
@Override
public List<CommentVO> getList(long bno) {
// TODO Auto-generated method stub
return cdao.getList(bno);
}
@Override
public int modify(CommentVO cvo) {
// TODO Auto-generated method stub
return cdao.modify(cvo);
}
@Override
public int delete(long cno) {
// TODO Auto-generated method stub
return cdao.delete(cno);
}
// @Override
// public PagingHandler getList(long bno, PagingVO pgvo) {
// // ph 객체 안에 cmtList / totalCount 구해오기
// List<CommentVO> cmtList = cdao.getList(bno, pgvo);
// int totalCount = cdao.getTotalCount(bno);
// PagingHandler ph = new PagingHandler(totalCount, pgvo, cmtList);
// return ph;
// }
}
▣ CommentDAO.java
package com.ezen.spring.dao;
import java.util.List;
//import org.apache.ibatis.annotations.Param;
import com.ezen.spring.domain.CommentVO;
//import com.ezen.spring.domain.PagingVO;
public interface CommentDAO {
int post(CommentVO cvo);
List<CommentVO> getList(long bno);
int modify(CommentVO cvo);
int delete(long cno);
// List<CommentVO> getList(@Param("bno") long bno, @Param("pgvo") PagingVO pgvo);
int getTotalCount(long bno);
}
▣ commentMapper.xml
<?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="com.ezen.spring.dao.CommentDAO">
<insert id="post">
insert into comment(bno, writer, content) values(#{bno}, #{writer}, #{content})
</insert>
<select id="getList" resultType="com.ezen.spring.domain.CommentVO">
select * from comment where bno = #{bno} order by cno desc
</select>
<!-- <select id="getList" resultType="com.ezen.spring.domain.CommentVO">
select * from comment where bno = #{bno} order by cno desc limit #{pgvo.pageStart}, #{pgvo.qty}
</select> -->
<select id="getTotalCount" resultType="int">
select count(cno) from comment where bno = #{bno}
</select>
<update id="modify">
update comment set content = #{content}, reg_date = now() where cno = #{cno}
</update>
<delete id="delete">
delete from comment where cno = #{cno}
</delete>
</mapper>
▣ boardDetailComment.xml
- VSCode와 연동 (연동 이후 node와 연결을 허락하지 말 것!! 허락할 시 재앙을 맛봄)
/**
*
*/
console.log("boardDetailComment.js in");
console.log("vscode 연동 성공");
document.getElementById('cmtAddBtn').addEventListener('click', ()=>{
const cmtText = document.getElementById('cmtText');
const cmtWriter = document.getElementById('cmtWriter');
if(cmtText.value == null || cmtText.value == ''){
alert('댓글을 입력해주세요.');
cmtText.focus();
return false;
}
let cmtData = {
bno: bnoVal,
writer: cmtWriter.innerText,
content: cmtText.value
}
console.log(cmtData);
postCommentToServer(cmtData).then(result => {
if(result == '1'){
alert("댓글 등록 성공");
cmtText.value="";
// 댓글 뿌리기
spreadCommendList(bnoVal);
}
})
});
function spreadCommendList(bno, page=1){
getCommentListFromServer(bno, page).then(result =>{
console.log(result);
// 댓글 뿌리기
const ul = document.getElementById('cmtListArea');
if(result.length > 0){
ul.innerHTML = ""; // 반복 전에 기존 샘플 버리기
for(let cvo of result){
let li = `<li class="list-group-item" data-cno=${cvo.cno}>`;
li += `<div class="me-2 me-auto">${cvo.cno}.`;
li += `<div class="fw-bold">${cvo.writer}</div>`;
li += `${cvo.content} </div>`;
li += `<span class="badge text-bg-primary rounded-pill">${cvo.regDate}</span>`;
// 수정 삭제 버튼 추가
li += `<button type="button" data-cno=${cvo.cno} class="btn btn-outline-warning btn-sm mod" data-bs-toggle="modal" data-bs-target="#myModal">%</button>`;
li += `<button type="button" data-cno=${cvo.cno} class="btn btn-outline-danger btn-sm del">X</button>`;
li += `</li>`;
ul.innerHTML += li;
}
}else{
ul.innerHTML = `<div>Comment List Empty</div>`;
}
})
}
// 수정 삭제
document.addEventListener('click', (e) => {
// console.log(e.target);
// 내가 클릭한 버튼의 객체를 모달창으로 전달
if(e.target.classList.contains('mod')){
// 내가 클릭한 버튼의 li 가져오기
// closest : 가장 가까운(나를 포함한) 태그 (부모태그)
let li = e.target.closest('li');
// nextSibling : 한 부모 안에서의 다음 형제 값 찾기
let cmtText = li.querySelector('.fw-bold').nextSibling;
console.log(cmtText);
document.getElementById('cmtTextMod').value = cmtText.nodeValue;
let cno = li.dataset.cno;
let cmtWriter = li.querySelector('.fw-bold').innerText;
document.getElementById('cmtWriterMod').innerText = `no.${cno} <b>${cmtWriter}</b>`;
// cmtModBtn => cno 값을 dataset으로 달기
document.getElementById('cmtModBtn').setAttribute("data-cno", cno);
}
if(e.target.id == 'cmtModBtn'){
let cmtData = {
cno : e.target.dataset.cno,
content : document.getElementById('cmtTextMod').value
};
console.log(cmtData);
updateCommentToServer(cmtData).then(result =>{
if(result == '1'){
alert("댓글 수정 성공");
}else{
alert("댓글 수정 실패");
}
// 모달창 닫기 : btn-close라는 객체를 클릭해라
document.querySelector('.btn-close').click();
// 댓글 뿌리기
spreadCommendList(bnoVal);
})
}
if(e.target.classList.contains('del')){
// cno만 있으면 됨.
let li = e.target.closest('li');
let cno = li.dataset.cno;
removeCommentToServer(cno).then(result => {
if(result == '1'){
alert("댓글 삭제 성공");
}else{
alert("댓글 삭제 실패");
}
// 댓글 뿌리기
spreadCommendList(bnoVal);
})
}
if(e.target.id == 'moreBtn'){
let page = e.target.dataset.page;
}
})
async function updateCommentToServer(cmtData) {
try{
const url = "/comment/modify";
const config={
method: 'put',
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body: JSON.stringify(cmtData)
};
const resp = await fetch(url, config);
const result = await resp.text(); // isOk
return result;
} catch (error){
console.log(error);
}
}
// delete 메서드 사용
async function removeCommentToServer(cno) {
try{
const url = "/comment/"+cno;
const config = {
method : 'delete'
}
const resp = await fetch(url, config);
// const resp = await fetch("/comment/"+cno, {method : 'delete'});
const result = await resp.text(); // isOk
return result;
} catch(error) {
console.log(error);
}
}
// get은 생략가능.
async function getCommentListFromServer(bno, page) {
try{
const resp = await fetch("/comment/"+bno+"/"+page);
const result = await resp.json();
return result;
} catch (error){
console.log(error);
}
}
async function postCommentToServer(cmtData) {
try{
const url = "/comment/post";
const config = {
method: "post",
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body: JSON.stringify(cmtData)
};
const resp = await fetch(url, config);
console.log(resp);
const result = await resp.text(); // isOk
return result;
} catch(error){
console.log(error);
}
}
▣ detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../layout/header.jsp"/>
<body>
<div class="container-md">
<h1>Board Detail Page...</h1>
<div class="mb-3">
<label for="t" class="form-label">title</label>
<input type="text" class="form-control" id="t" value="${bvo.title}" readonly>
</div>
<div class="mb-3">
<label for="w" class="form-label">writer</label>
<input type="text" class="form-control" id="w" value="${bvo.writer}" readonly>
<span class="bodge text-bg-Info">${bvo.regDate}</span>
</div>
<div class="mb-3">
<label for="c" class="form-label">content</label>
<textarea class="form-control" id="c" rows="3" readonly>${bvo.content}</textarea>
</div>
<a href="/board/modify?bno=${bvo.bno }"><button type="button" class="btn btn-success">modify</button></a>
<a href="/board/delete?bno=${bvo.bno }"><button type="button" class="btn btn-danger">delete</button></a>
<!-- comment line -->
<!-- comment post -->
<div class="input-group mb-3">
<span class="input-group-text" id="cmtWriter">tester1@tester.com</span>
<input type="text" id="cmtText" class="form-control" placeholder="Add Comment" aria-label="Username" aria-describedby="basic-addon1">
<button type="button" id="cmtAddBtn" class="btn btn-success">post</button>
</div>
<br>
<hr>
<!-- comment print-->
<ul class="list-group list-group-flush" id="cmtListArea">
<li class="list-group-item">
<div class="me-2 me-auto">
<div class="fw-bold">writer</div>
Content
</div>
<span class="badge text-bg-primary rounded-pill">regDate</span>
</li>
</ul>
<!-- 댓글 더보기 버튼 -->
<div>
<button type="button" id="moreBtn" data-page="1" class="btn btn-dark" style="visibility:hidden">More +</button>
</div>
<!-- model line -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="cmtWriterMod">Writer</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="text" id="cmtTextMod" class="form-control">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="cmtModBtn" class="btn btn-primary">changes</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
let bnoVal = `<c:out value="${bvo.bno}" />`;
console.log(bnoVal);
</script>
<script type="text/javascript" src="/resources/js/boardDetailComment.js"></script>
<script type="text/javascript">
spreadCommendList(bnoVal);
</script>
</div>
</body>
<jsp:include page="../layout/footer.jsp"/>
▣ pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ezen</groupId>
<artifactId>spring</artifactId>
<name>spring_study_javaClass</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>11</java-version>
<org.springframework-version>5.3.10</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>2.0.7</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<!-- logback-classic 1.4.5 / logback-core / log4jdbc-log4j2-jdbc4.1-1.16 -->
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.5</version>
<!-- <scope>test</scope> -->
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency> -->
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<!-- 여기서부터 추가 dependency -->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
<!-- DB 관련 -->
<!-- mysql-connector-j-8.0.33 / mybatis-3.5.10 / mybatis-spring-2.0.6 -->
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<!-- spring-JDBC-5.3.10 / spring-Test-5.3.10 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- Hikari CP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>6.0.0</version>
</dependency>
<!-- 댓글관련 : json 파싱 역할 -->
<!-- jackson-databind-2.13.0 jackson-dataformat-xml -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.13.1</version>
</dependency>
<!-- 파일관련, 시큐리티관련, 스케쥴러관련 -->
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>11</source>
<target>11</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
<!-- 플러그인 추가 : web.xml이 없어도 class를 통해서 설정정보를 읽을 수 있게 추가 설정-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
▷ 출력
'Java > Spring' 카테고리의 다른 글
Spring 기초(scheduler) - AWS 풀스택 과정 70일차 (0) | 2024.11.04 |
---|---|
Spring 기초(file) - AWS 풀스택 과정 69일차 (0) | 2024.11.01 |
Spring 기초(paging, search) - AWS 풀스택 과정 67일차 (0) | 2024.10.30 |
Spring 설정 및 기초2 - AWS 풀스택 과정 66일차 (0) | 2024.10.29 |
Spring 설정 및 기초 - AWS 풀스택 과정 65일차 (0) | 2024.10.28 |