글쓰기를 하려면 insert로직을 짜야할 것이고, save 메소드를 실행하면 되는데 로그인했을 때 자신의 userId에 맞게 저장이 되야한다. 그 때 Session을 이용해서 userId 값을 구해서 Save 로직을 수행하면 된다.
<!-- 글쓰기 title, content, userId필요, createDate -->
<insert id="save">
INSERT INTO post(userId, title, content, createDate)
VALUES(#{userId}, #{title}, #{content}, now())
</insert>
title과 content는 form태그의 name 데이터로 가져오고, userId는 session에서 가져온다.
userId는 자동으로 저장되는 것이 아니니까 찾아서 설정해서 저장시켜줘야됨!!
public void save(Post post);
// writePage
@GetMapping("/write")
public String writePage() {
return "board/write";
}
// key : value로 들어올 때
// 스프링에서 key : value로 오는 값을 받아서 자동으로 객체로 받아줄 수 있다.
// write : 글쓰기
@PostMapping("/writeProc")
public String write(Post post, HttpSession session) {
User principal = (User)session.getAttribute("principal");
//저장했던 세션 값을 가져옴
System.out.println(principal);
Post requestPost = Post.builder()
.title(post.getTitle())
.content(post.getContent())
.userId(principal.getId())
.build();
postRepository.save(requestPost);
return "redirect:/";
}
write 성공