header.jsp
글쓰기 a태그를 누르게되면 href주소를타고 글쓰기 페이지로 넘어가게된다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="isAuthenticated()">
<sec:authentication property="principal" var="principal"/>
</sec:authorize>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta id="_csrf" name="${_csrf.parameterName}" content="${_csrf.token}">
<meta id="_csrf_header" name="_csrf_header" content="${_csrf.headerName}">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="/">HOME</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<c:choose>
<c:when test="${empty principal}">
<li class="nav-item"><a class="nav-link" href="/auth/login_form">로그인</a></li>
<li class="nav-item"><a class="nav-link" href="/auth/join_form">회원가입</a></li>
</c:when>
<c:otherwise>
<li class="nav-item"><a class="nav-link" href="/board/save_form">글쓰기</a></li>
<li class="nav-item"><a class="nav-link" href="/user/update_form">회원정보</a></li>
<li class="nav-item"><a class="nav-link" href="/logout">로그아웃</a></li>
</c:otherwise>
</c:choose>
</ul>
</div>
</nav>
<br>
save_form.jsp
글을쓸때 여러가지 도구를 사용할 수 있도록 라이브러리를 땡겨와서 사용을 할 수 있다.
글을 다 작성하면 글쓰기 a태그를 누르게되면 id값을 할당하여 js에서 데이터 처리를 해준다.
썸머노트 라이브러리
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
<script>
$('.content').summernote({
placeholder: '내용을 입력해주세요',
tabsize: 2,
height: 300
});
</script>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp" %>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
<div class="container">
<form action="/api/board">
<div class="form-group" >
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control" >
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" id="content" rows="5" class="form-control content" ></textarea>
</div>
<!-- <input type="submit" class="btn btn-primary" value="글쓰기 완료"> -->
</form>
<button type="button" id="btn--save" class="btn btn-primary" > 글쓰기 완료</button>
</div>
<script>
$('.content').summernote({
placeholder: '내용을 입력해주세요',
tabsize: 2,
height: 300
});
</script>
<script type="text/javascript" src="/js/board.js"></script>
<%@ include file="../layout/footer.jsp" %>
board.js
글쓰기 완료 버튼을 누르게되면 ajax통신을 통해서 url주소를 타고 db에 접근하여 저장하도록 처리를 해준다. db에 저장이
잘되었으면 context경로로 페이지를 리다이렉트 해준다.
let index = {
init: function() {
$("#btn--save").bind("click",() => {
this.save();
});
},
save: function() {
let data = {
title: $("#title").val(),
content: $("#content").val()
};
// ajax 통신 요청
$.ajax({
type: "POST",
url: "/api/board",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(data, textSatus, xhr) {
if (data.status == "OK") {
alert("글쓰기 성공");
location.href = "/";
}
}).fail((error) => {
console.log(error);
console.log(data.title);
console.log(data.content);
alert(error.responseJSON.error);
});
}
}
index.init();
BoardApiController
요청시 body에 Board, 누가 로그인했는지 접속자의 세션이 필요하다. 두개의 데이터를 매개변수에 담아 요청해준다.
package com.demo.t1.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.demo.t1.auth.PrincipalDetail;
import com.demo.t1.dto.Board;
import com.demo.t1.dto.ResponseDto;
import com.demo.t1.service.BoardService;
@RestController
public class BoardApiController {
@Autowired
private BoardService boardService;
@PostMapping("/api/board")
ResponseDto<Integer> save(@RequestBody Board board, @AuthenticationPrincipal PrincipalDetail principalDetail) {
System.err.println("게시글 작성 api");
int result = boardService.write(board, principalDetail.getUser());
return new ResponseDto<Integer>(HttpStatus.OK,result);
}
}
BoardRepository
package com.demo.t1.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.demo.t1.dto.Board;
public interface BoardRepository extends JpaRepository<Board, Integer>{
}
BoardService
게시글을 작성하기위해서는 Board, User가 필요하다. Board에는 게시글제목, 게시글내용이 필요하고 User에서는 어떤사람이 썻는지 데이터가 필요하다.
댓글