1 page site~~
index.jsp => 글목록. 가장 위에 글작성 폼이 있음.
♥
< 방명록 >
작성폼 -------------------
- 작성자 :
- 글 비밀번호 :
- 내용 :
- 작성버튼 (--> ajax 요청)
-------------------------
< 글 목록 >
- 글번호 / 좋아요 수 / 좋아요 버튼
- 작성자
- 작성일
- 내용
[수정][삭제] (--> 글 비밀번호 물어봄.
수정 > 일치 -> 수정폼 뜨기
삭제 > 불일치 -> 취소 alert)
(수정폼에서 글 내용만 수정)
(수정폼의 수정버튼은 수정완료. 취소버튼 누르면 수정폼 사라짐)
....
..
.
pom.xml
더보기
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<!-- <version>6.0.0</version>-->
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp.jstl/jakarta.servlet.jsp.jstl-api -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<!-- <version>3.0.0</version>-->
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.web/jakarta.servlet.jsp.jstl -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<!-- <version>3.0.1</version>-->
</dependency>
application.properties
더보기
# port
server.port=8081
# JSP view
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp
# oracle set
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=hr
spring.datasource.password=hr
#encoding
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
GuestbookVo.java
더보기
package com.example.demo.guestbook;
import java.sql.Date;
public class GuestbookVo {
private int num;
private String writer;
private Date w_date;
private String pwd;
private String content;
private int cnt;
public GuestbookVo() {}
public GuestbookVo(int num, String writer, Date w_date, String pwd, String content, int cnt) {
super();
this.num = num;
this.writer = writer;
this.w_date = w_date;
this.pwd = pwd;
this.content = content;
this.cnt = cnt;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public Date getW_date() {
return w_date;
}
public void setW_date(Date w_date) {
this.w_date = w_date;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
@Override
public String toString() {
return "GuestbookVo [num=" + num + ", writer=" + writer + ", w_date=" + w_date + ", pwd=" + pwd + ", content="
+ content + ", cnt=" + cnt + "]";
}
}
GuestbookDao.java
더보기
package com.example.demo.guestbook;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class GuestbookDao {
@Autowired
private JdbcTemplate temp;
public class GuestbookMapper implements RowMapper<GuestbookVo>{
@Override
public GuestbookVo mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
return new GuestbookVo(rs.getInt(1), rs.getString(2), rs.getDate(3), rs.getString(4), rs.getString(5), rs.getInt(6));
}
}
// 글 번호로 글 검색 (수정폼 내용 띄우기)
public GuestbookVo select (int num) {
String sql = "select * from guestbook where num=?";
GuestbookVo vo = null;
try {
vo = temp.queryForObject(sql, new GuestbookMapper(), num);
} catch (EmptyResultDataAccessException e) {
System.out.println("없는 글.");
}
return vo;
}
// 전체 검색
public ArrayList<GuestbookVo> selectAll (){
String sql = "select * from guestbook order by num desc";
return (ArrayList<GuestbookVo>) temp.query(sql, new GuestbookMapper());
}
// 글 작성
public void insert (GuestbookVo vo) {
String sql = "insert into guestbook values(seq_guestbook.nextval, ?, sysdate, ?, ?, 0)";
temp.update(sql, new Object[] {vo.getWriter(), vo.getPwd(), vo.getContent()});
}
// 글 내용 수정
public void update (String content, int num) {
String sql = "update guestbook set content=? where num=?";
temp.update(sql, content, num);
}
// 글 좋아요 수정
public void updateCnt (int num) {
String sql = "update guestbook set cnt = cnt+1 where num=?";
temp.update(sql, num);
}
// 글 삭제
public void delete (int num) {
String sql = "delete from guestbook where num=?";
temp.update(sql, num);
}
}
GuestbookService.java
더보기
package com.example.demo.guestbook;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GuestbookService {
@Autowired
private GuestbookDao dao;
// 글 번호로 글 검색 (수정폼 내용 띄우기)
public GuestbookVo get (int num) {
return dao.select(num);
}
// 전체 검색
public ArrayList<GuestbookVo> getAll (){
return dao.selectAll();
}
// 글 작성
public void add (GuestbookVo vo) {
dao.insert(vo);
}
// 글 내용 수정
public void edit (String content, int num) {
dao.update(content, num);
}
// 글 좋아요 수정
public void editCnt (int num) {
dao.updateCnt(num);
}
// 글 삭제
public void del (int num) {
dao.delete(num);
}
}
HomeController.java
package com.example.demo;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.guestbook.GuestbookService;
import com.example.demo.guestbook.GuestbookVo;
@Controller
public class HomeController {
@Autowired
private GuestbookService service;
@RequestMapping("/")
public String root(ModelMap map) {
ArrayList<GuestbookVo> list = service.getAll();
map.addAttribute("list", list);
return "index";
}
}
GuestbookController.java
package com.example.demo.guestbook;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GuestbookController {
@Autowired
private GuestbookService service;
@ResponseBody
@PostMapping("/add")
public Map add(GuestbookVo vo) {
service.add(vo);
ArrayList<GuestbookVo> list = service.getAll();
Map map = new HashMap();
map.put("list", list);
return map;
}
@PostMapping("/edit")
public String edit(String content, int num) {
service.edit(content, num);
return "index";
}
@GetMapping("/del")
public String del(int num) {
service.del(num);
return "index";
}
@ResponseBody
@GetMapping("/like")
public Map like(int num) {
service.editCnt(num);
GuestbookVo vo = service.get(num);
Map map = new HashMap();
map.put("like", vo.getCnt());
return map;
}
}
index.jsp
<%@ 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
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#editf').hide();
//글 작성 버튼 누르면~
//$(document).on("click", "#btn", function(){
$('#btn').click(function(){
let formData = $('#bookf').serialize();
alert(formData);
$.ajax({
url: '/add',
type: 'post',
data: formData,
dataType: 'JSON',
success: function(result){
let arr= result.list;
let txt = '';
for(let obj of arr){
txt += '<div id="div_' + obj.num + '" pwd="'+obj.pwd+'">';
txt += "<table border='1'><tr><th>"+obj.num+"</th>";
txt += "<td id='like_" + obj.num + "'> " +obj.cnt+" <input type='button' value='♥' onclick='like("+obj.num+")'></td></tr>";
txt += "<tr><th>작성자</th><td>"+obj.writer+"</td></tr>";
txt += "<tr><th>작성일</th><td>"+obj.w_date+"</td></tr>";
txt += "<tr><th>내용</th><td id='content_"+obj.num+"'>"+obj.content+"</td></tr>";
txt += '</table>';
txt += "<input type='button' onclick='editForm("+obj.num+")' value='수정'>";
txt += "<input type='button' onclick='del("+obj.num+")' value='삭제'></div>";
}
$('#board').html(txt);
$('#writer').val('');
$('#pwd').val('');
$('#content').val('내용을 입력하세요.');
},
error: function(req, status){
alert(status);
}
});
})
// 수정폼의 취소버튼 누르면~
$('#cancel').click(function(){
$('#new').val('');
$('body').append($('#editf'));
$('#editf').hide();
});
// 수정폼의 수정버튼 누르면~
$('#edit').click(function(){
let num = $('#num').val();
$.ajax({
url: '/edit',
type: 'post',
data: {'content':$('#new').val(), 'num':num},
success: function(result){
$('#content_'+num).text($('#new').val());
$('#new').val('');
$('body').append($('#editf'));
$('#editf').hide();
},
error: function(req, status){
alert(status);
}
});
})
})
// 글 수정버튼 누르면 수정폼 띄우기..
function editForm(num){
let pwd = prompt('글 비밀번호');
if($('#div_'+num).attr('pwd')==pwd){
$('#div_'+num).append($('#editf'));
let c = $('#content_'+num).text();
$('#new').val(c); // 수정폼에 원글 내용 띄위기!
$('#num').val(num); // 글번호를 수정글 번호에 넣기 -> 수정할 때 글번호 보내줘야 해서!~
$('#editf').show();
} else {
alert('비밀번호가 맞지 않습니다.');
}
}
function del(num){
let pwd = prompt('글 비밀번호');
if($('#div_'+num).attr('pwd')==pwd){
// 서버로 가야함~
$.ajax({
url: '/del',
type: 'get',
data: {'num':num},
success: function(result){
$('#div_'+num).remove();
alert(num+" 번글 삭제")
},
error: function(req, status){
alert(status);
}
});
} else {
alert('비밀번호가 맞지 않습니다.');
}
}
// 좋아요 버튼 누르면~
function like(num){
// 좋아요 수 올라가야 함~
// 서버 가서 업데이트 하고
// 돌아와서 변한 수 보여주고
$.ajax({
url: '/like',
type: 'get',
data: {'num':num},
dataType: 'JSON',
success: function(result){
let txt = '';
txt += result.like + " <input type='button' value='♥' onclick='like(" + num + ")'>";
$('#like_'+num).html(txt);
alert("좋아용~~");
},
error: function(req, status){
alert(status);
}
});
}
</script>
</head>
<body>
<!-- 작성폼 -->
<form id="bookf">
작성자: <input type="text" name="writer" id="writer"><br/>
글 비밀번호: <input type="text" name="pwd" id="pwd"><br/>
내용: <textarea rows="3" cols="20" name="content" id="content">내용을 입력하세요.</textarea><br/>
<input type="button" id="btn" value="작성">
</form>
<!-- 수정폼 -->
<form id="editf">
<input type="hidden" name="num" id="num">
수정할 내용: <textarea rows="3" cols="20" name="content" id="new"></textarea><br/>
<input type="button" id="edit" value="수정">
<input type="button" id="cancle" value="취소">
</form>
<!-- 글 목록 -->
<div id="board">
<c:forEach var="vo" items="${list}">
<div id="div_${vo.num}" pwd="${vo.pwd}">
<table border="1">
<tr><th>${vo.num}</th>
<td id="like_${vo.num }">${vo.cnt} <input type="button" value="♥" onclick="like(${vo.num })"></td></tr>
<tr><th>작성자</th><td>${vo.writer }</td></tr>
<tr><th>작성일</th><td>${vo.w_date }</td></tr>
<tr><th>내용</th><td id="content_${vo.num }">${vo.content }</td></tr>
</table>
<input type="button" onclick="editForm(${vo.num})" value="수정">
<input type="button" onclick="del(${vo.num})" value="삭제">
</div>
</c:forEach>
</div>
</body>
</html>