일단 글쓰기 화면을 만들기.
writeForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container">
<form>
<div class="form-group">
<label for="title">Title</label> <input type="text" class="form-control" id="title" placeholder="제목을 입력해주세요." required>
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea class="form-control summernote" rows="5" id="content"></textarea>
</div>
</form>
<button id="btn-save" class="btn btn-primary">글쓰기 완료</button>
</div>
<script>
$('.summernote').summernote({
placeholder: '내용을 입력해주세요.',
tabsize: 2,
height: 400
});
</script>
<script src="/js/board.js"></script>
<%@ include file="../layout/footer.jsp"%>
위지윅 에디터인 썸머노트를 사용했다. bootstrap4를 지원하기 때문에 알맞은 코드를 가져왔다.
글쓰기 완료 버튼을 누르면 실행될 .js를 만든다.
let index = {
init: function() {
$("#btn-save").on("click", ()=>{
this.save();
});
},
save: function() {
let data = {
title: $("#title").val(),
content: $("#content").val(),
};
$.ajax({
type: "POST",
url: "/api/boardWrite",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(resp){
alert("글쓰기가 완료되었습니다.");
location.href="/";
}).fail(function(error){
alert(JSON.stringify(error));
});
}
}
index.init();
BoardService에서 사용할 BoardRepository를 만든다.
package com.pure.blog.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.pure.blog.model.Board;
public interface BoardRepository extends JpaRepository<Board, Integer> { //Board 테이블이 관리하는 repo, PK는 Integer
}
BoardService를 만든다.
package com.pure.blog.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pure.blog.model.Board;
import com.pure.blog.model.User;
import com.pure.blog.repository.BoardRepository;
//component-scan으로 Bean에 등록. (IoC)
@Service
public class BoardService {
@Autowired
private BoardRepository boardRepository;
@Transactional //내부 기능이 모두 정상작동 하면 commit, 하나라도 실패하면 rollback
public void 글쓰기(Board board, User user) {
board.setCount(0);
board.setUser(user);
boardRepository.save(board);
}
}
ajax요청을 처리할 컨트롤러를 만든다.
BoardApiController.java
package com.pure.blog.controller.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.pure.blog.config.auth.PrincipalDetail;
import com.pure.blog.dto.ResponseDto;
import com.pure.blog.model.Board;
import com.pure.blog.service.BoardService;
@RestController
public class BoardApiController {
@Autowired
private BoardService boardService;
@PostMapping("/api/boardWrite")
public ResponseDto<Integer> save(@RequestBody Board board, @AuthenticationPrincipal PrincipalDetail principal) {
boardService.글쓰기(board, principal.getUser());
return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
}
}
보드서비스의 글쓰기 메서드를 사용할 때 User 정보를 넘겨줘야 하기 때문에 시큐리티가 가지고 있는 PrincipalDetail 객체 안에 있는 User를 .getUser로 넘긴다.
@Getter
public class PrincipalDetail implements UserDetails {
이 때문에 PrincipalDetail 클래스에 @getter를 추가해 뒀음.
그리고 보드컨트롤러에 글쓰기 버튼을 눌렀을 때 이동할 페이지를 지정.
BoardController.java
package com.pure.blog.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BoardController {
@GetMapping({"","/"})
public String index() {
return "index";
}
@GetMapping("/board/writeForm")
public String saveForm() {
return "board/writeForm";
}
}
'취업 준비 > Spring boot' 카테고리의 다른 글
32. 글 상세내용 보여주기 (0) | 2022.01.27 |
---|---|
31. 글 목록 출력, 페이징 처리 (0) | 2022.01.27 |
29. 스프링 시큐리티를 사용한 로그인 (0) | 2022.01.26 |
28. XSS와 CSRF (0) | 2022.01.26 |
27. 비밀번호 해쉬 후 회원가입하기 (0) | 2022.01.26 |