├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── coco │ │ └── board │ │ ├── BoardApplication.java │ │ ├── application │ │ ├── CommentService.java │ │ ├── PostsService.java │ │ ├── UserService.java │ │ ├── dto │ │ │ ├── CommentDto.java │ │ │ ├── PostsDto.java │ │ │ └── UserDto.java │ │ ├── security │ │ │ ├── auth │ │ │ │ ├── CustomAuthFailureHandler.java │ │ │ │ ├── CustomUserDetails.java │ │ │ │ ├── CustomUserDetailsService.java │ │ │ │ ├── LoginUser.java │ │ │ │ └── LoginUserArgumentResolver.java │ │ │ └── oauth │ │ │ │ ├── CustomOAuth2UserService.java │ │ │ │ └── OAuthAttributes.java │ │ └── validator │ │ │ ├── AbstractValidator.java │ │ │ └── CustomValidators.java │ │ ├── domain │ │ ├── BaseTimeEntity.java │ │ ├── Comment.java │ │ ├── Posts.java │ │ ├── Role.java │ │ └── User.java │ │ ├── infrastructure │ │ ├── config │ │ │ ├── SecurityConfig.java │ │ │ └── WebConfig.java │ │ └── persistence │ │ │ ├── CommentRepository.java │ │ │ ├── PostsRepository.java │ │ │ └── UserRepository.java │ │ └── presentation │ │ ├── CommentApiController.java │ │ ├── PostsApiController.java │ │ ├── PostsIndexController.java │ │ ├── UserApiController.java │ │ └── UserController.java └── resources │ ├── application.properties │ ├── static │ ├── css │ │ └── app.css │ ├── img │ │ └── naver.ico │ └── js │ │ └── app.js │ └── templates │ ├── comment │ ├── form.mustache │ └── list.mustache │ ├── index.mustache │ ├── layout │ ├── footer.mustache │ └── header.mustache │ ├── posts │ ├── posts-page.mustache │ ├── posts-read.mustache │ ├── posts-search.mustache │ ├── posts-update.mustache │ └── posts-write.mustache │ └── user │ ├── user-join.mustache │ ├── user-login.mustache │ └── user-modify.mustache └── test └── java └── com └── coco └── board ├── BoardApplicationTests.java ├── controller └── PostsApiControllerTest.java ├── domain ├── CommentRepositoryTest.java ├── PostsRepositoryTest.java └── UserRepositoryTest.java ├── infrastructure └── config │ └── SecurityConfigTest.java └── service └── PostsServiceTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | application-oauth.properties 8 | 9 | ### STS ### 10 | .apt_generated 11 | .classpath 12 | .factorypath 13 | .project 14 | .settings 15 | .springBeans 16 | .sts4-cache 17 | bin/ 18 | !**/src/main/**/bin/ 19 | !**/src/test/**/bin/ 20 | 21 | ### IntelliJ IDEA ### 22 | .idea 23 | *.iws 24 | *.iml 25 | *.ipr 26 | out/ 27 | !**/src/main/**/out/ 28 | !**/src/test/**/out/ 29 | 30 | ### NetBeans ### 31 | /nbproject/private/ 32 | /nbbuild/ 33 | /dist/ 34 | /nbdist/ 35 | /.nb-gradle/ 36 | 37 | ### VS Code ### 38 | .vscode/ 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # :paperclip: Basic board Project 2 | > 전반적인 웹의 기본 소양이 되는 게시판 프로젝트입니다. 3 | 4 | ![메인 화면](https://user-images.githubusercontent.com/59757689/149616313-dbeace05-67dc-4d70-b6a1-630d601b6455.PNG) 5 | 6 | ## 목차 7 | - [들어가며](#들어가며) 8 | - [프로젝트 소개](#1-프로젝트-소개) 9 | - [프로젝트 기능](#2-프로젝트-기능) 10 | - [사용 기술](#3-사용-기술) 11 | - [백엔드](#3-1-백엔드) 12 | - [프론트엔드](#3-2-프론트엔드) 13 | - [실행 화면](#4-실행-화면) 14 | 15 | 16 | - [구조 및 설계](#구조-및-설계) 17 | - [패키지 구조](#1-패키지-구조) 18 | - [DB 설계](#2-db-설계) 19 | - [API 설계](#3-api-설계) 20 | 21 | - [개발 내용](#개발-내용) 22 | 23 | - [마치며](#마치며) 24 | - [프로젝트 보완사항](#1-프로젝트-보완사항) 25 | - [후기](#2-후기) 26 | 27 | ## 들어가며 28 | ### 1. 프로젝트 소개 29 | 30 | 프로젝트를 시작하게 된 계기는 웹 프로그래밍의 기본 소양이라 할 수 있는 게시판을 직접 만들어보며 배우고자 시작하게 되었습니다. 31 | 독학으로 관련 기술들을 학습한 이후 제작한 개인 프로젝트이기 때문에 개인적인 만족감을 가지고 있는 프로젝트입니다. 32 | 33 | ### 2. 프로젝트 기능 34 | 35 | 프로젝트의 주요 기능은 다음과 같습니다. 36 | - **게시판 -** CRUD 기능, 조회수, 페이징 및 검색 처리 37 | - **사용자 -** Security 회원가입 및 로그인, OAuth 2.0 구글, 네이버 로그인, 회원정보 수정, 회원가입시 유효성 검사 및 중복 검사 38 | - **댓글 -** CRUD 기능 39 | 40 | ### 3. 사용 기술 41 | 42 | #### 3-1 백엔드 43 | 44 | ##### 주요 프레임워크 / 라이브러리 45 | - Java 11 46 | - SpringBoot 2.5.6 47 | - JPA(Spring Data JPA) 48 | - Spring Security 49 | - OAuth 2.0 50 | 51 | ##### Build Tool 52 | - Gradle 7.2 53 | 54 | ##### DataBase 55 | - MySQL 8.0.19 56 | 57 | #### 3-2 프론트엔드 58 | - Html/Css 59 | - JavaScript 60 | - Mustache 61 | - Bootstrap 4.3.1 62 | 63 | 64 | ### 4. 실행 화면 65 |
66 | 게시글 관련 67 | 68 | 69 | **1. 게시글 전체 목록** 70 | ![image](https://user-images.githubusercontent.com/59757689/156975336-c37c9866-bba2-4c69-9a3f-230339a80d5a.png) 71 | 전체 목록을 페이징 처리하여 조회할 수 있다. 72 | 73 | **2. 게시글 등록** 74 | ![image](https://user-images.githubusercontent.com/59757689/156975408-413151f1-3bd8-4788-bc8e-77a2ffbd6eea.png) 75 | 로그인 한 사용자만 새로운 글을 작성할 수 있고, 작성 후 목록 화면으로 redirect한다. 76 | 77 | **3. 게시글 상세보기** 78 | ![image](https://user-images.githubusercontent.com/59757689/156975794-9d7ef3fd-7e03-4a24-99de-d3f7a99c8167.png) 79 | ![image](https://user-images.githubusercontent.com/59757689/156975849-f3e02f34-47ed-4b7a-92f5-83ee66bed2bb.png) 80 | 본인이 작성한 글만 수정 및 삭제가 가능하다. 81 | 82 | **4. 게시글 수정 화면** 83 | ![image](https://user-images.githubusercontent.com/59757689/156975898-2f17bc37-df52-418e-8a84-dc17cec37070.png) 84 | ![image](https://user-images.githubusercontent.com/59757689/156975948-954960c8-987e-4364-a036-3c58cb66bbdd.png) 85 | ![image](https://user-images.githubusercontent.com/59757689/156975965-da3681c1-1a0d-4159-865a-b5c202b1f7ee.png) 86 | 제목과 내용만 수정할 수 있게 하고, Confirm으로 수정 여부를 확인 후 상세보기 화면으로 redirect 한다. 87 | 목록 버튼을 누를 시 상세보기 화면으로 돌아간다. 88 | 89 | **5. 게시글 삭제 화면** 90 | ![image](https://user-images.githubusercontent.com/59757689/156976055-d6e8f6bd-9bda-4fc8-bb5f-3ea60d9f2f5d.png) 91 | ![image](https://user-images.githubusercontent.com/59757689/156976074-c27f90c8-c8e0-45b9-9d04-e3541a14b8c2.png) 92 | Confirm으로 삭제할지 확인하고, 삭제 후 전체 목록 리스트 화면으로 redirect 한다. 93 | 94 | **6. 게시글 검색 화면** 95 | ![image](https://user-images.githubusercontent.com/59757689/156976190-1dac1678-3cf4-4d21-9f3b-d5228b7d50ef.png) 96 | 검색 키워드에 포함된 글을 모두 보여준다. 97 | 98 | **6-1. 게시글 검색 후 페이징 화면** 99 | ![image](https://user-images.githubusercontent.com/59757689/156976258-c4b28ef3-fd6e-4ebe-834c-d5c6bce4c02c.png) 100 | ![image](https://user-images.githubusercontent.com/59757689/156976314-c6733cb8-7aac-4502-88d4-02730f88021b.png) 101 | 검색된 게시글이 많을 경우 다음과 같이 페이징 처리되어 조회할 수 있다. 102 | 103 |
104 |
105 | 106 |
107 | 회원 관련 108 | 109 | **1. 회원가입 화면** 110 | ![image](https://user-images.githubusercontent.com/59757689/156976413-78b9e0e9-2ab1-47e0-a0cd-699ebacddb79.png) 111 | ![image](https://user-images.githubusercontent.com/59757689/156976436-fafec47f-3df3-4356-83d5-eb80e1aa2276.png) 112 | ![image](https://user-images.githubusercontent.com/59757689/156976548-3a440a6c-49d0-4e5c-9eb3-d5e3524c11b6.png) 113 | 회원가입 시 유효성 검사 및 중복확인을 진행하며 완료시 회원 정보를 저장하고 로그인 화면으로 이동한다. 114 | 115 | **2. 로그인 화면** 116 | ![image](https://user-images.githubusercontent.com/59757689/156976619-6988837d-0dfe-4600-a63c-2e287db9c88e.png) 117 | ![image](https://user-images.githubusercontent.com/59757689/156976909-51b0d06c-502f-4e42-b0dd-516834e43efe.png) 118 | 로그인 실패시 어떤 이유로 실패 했는지 메시지가 나오고, 로그인에 성공하면 게시글 전체 리스트 화면으로 redirect 한다. 119 | 120 | **2-1. OAuth 2.0 소셜 로그인 화면** 121 | ![image](https://user-images.githubusercontent.com/59757689/156976991-c517d254-b4b8-4a34-99fd-2684856f2a2d.png) 122 | ![image](https://user-images.githubusercontent.com/59757689/156977007-7b44d157-f29c-4a43-9fd3-aa6b743a8fb8.png) 123 | 구글과 네이버 로그인이 가능하다. 124 | 125 | **3. 회원정보 수정 화면** 126 | ![image](https://user-images.githubusercontent.com/59757689/156977253-d1a4de93-da30-4adf-8634-dfe10d0635a8.png) 127 | 닉네임과 비밀번호만 변경할 수 있고, 변경된 닉네임이 이미 사용중일 경우 alert으로 현재 사용 중임을 알려주고, 128 | 완료시 게시글 전체 리스트 화면으로 redirect 한다. 129 | 130 |
131 |
132 | 133 |
134 | 댓글 관련 135 | 136 | **1. 댓글 작성 화면** 137 | 미로그인 사용자 화면 138 | ![image](https://user-images.githubusercontent.com/59757689/156977476-37db357a-ac44-4b24-ad8c-a062d4fe99cf.png) 139 | ![image](https://user-images.githubusercontent.com/59757689/156977497-cc7fc2a7-e688-4733-b4c7-8aef4fba93e3.png) 140 | 댓글은 로그인 한 사용자만 달 수 있으며, 댓글 작성시 현재 페이지를 reload 한다. 141 | 142 | **2. 댓글 수정** 143 | ![image](https://user-images.githubusercontent.com/59757689/156977557-8a3dae77-9a8d-4fd3-824e-8ff22606609e.png) 144 | 다른 사용자는 다른 사람의 댓글을 수정/삭제할 수 없다. 145 | ![image](https://user-images.githubusercontent.com/59757689/156977567-fd983777-5b04-4f57-a815-c89a59697377.png) 146 | 수정은 댓글 작성자만이 할 수 있다. 수정 완료 후 현재 페이지를 reload 한다. 147 | 148 | **3. 댓글 삭제** 149 | ![image](https://user-images.githubusercontent.com/59757689/156977655-8125a317-344e-4721-a836-46b36df3a3b5.png) 150 | ![image](https://user-images.githubusercontent.com/59757689/156977661-5008733b-2932-4bfc-be01-60a33a093dc9.png) 151 | 삭제 또한 댓글 작성자만이 할 수 있다. 삭제 후 현재 페이지를 reload 한다. 152 | 153 |
154 |
155 | 156 | 157 | ## 구조 및 설계 158 | 159 | ### 1. 패키지 구조 160 | 161 |
162 | 163 | 패키지 구조 보기 164 | 165 | 166 | ``` 167 | 📦src 168 | ┣ 📂main 169 | ┃ ┣ 📂java 170 | ┃ ┃ ┗ 📂com 171 | ┃ ┃ ┃ ┗ 📂coco 172 | ┃ ┃ ┃ ┃ ┗ 📂board 173 | ┃ ┃ ┃ ┃ ┃ ┣ 📂application 174 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📂dto 175 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CommentDto.java 176 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsDto.java 177 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜UserDto.java 178 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📂security 179 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📂auth 180 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CustomAuthFailureHandler.java 181 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CustomUserDetails.java 182 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CustomUserDetailsService.java 183 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜LoginUser.java 184 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜LoginUserArgumentResolver.java 185 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📂oauth 186 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CustomOAuth2UserService.java 187 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜OAuthAttributes.java 188 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📂validator 189 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜AbstractValidator.java 190 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜CustomValidators.java 191 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CommentService.java 192 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsService.java 193 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜UserService.java 194 | ┃ ┃ ┃ ┃ ┃ ┣ 📂domain 195 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜BaseTimeEntity.java 196 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜Comment.java 197 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜Posts.java 198 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜Role.java 199 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜User.java 200 | ┃ ┃ ┃ ┃ ┃ ┣ 📂infrastructure 201 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📂config 202 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜SecurityConfig.java 203 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜WebConfig.java 204 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📂persistence 205 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CommentRepository.java 206 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsRepository.java 207 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜UserRepository.java 208 | ┃ ┃ ┃ ┃ ┃ ┣ 📂presentation 209 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CommentApiController.java 210 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsApiController.java 211 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsIndexController.java 212 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜UserApiController.java 213 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜UserController.java 214 | ┃ ┃ ┃ ┃ ┃ ┗ 📜BoardApplication.java 215 | ┃ ┗ 📂resources 216 | ┃ ┃ ┣ 📂static 217 | ┃ ┃ ┃ ┣ 📂css 218 | ┃ ┃ ┃ ┃ ┗ 📜app.css 219 | ┃ ┃ ┃ ┣ 📂img 220 | ┃ ┃ ┃ ┃ ┗ 📜naver.ico 221 | ┃ ┃ ┃ ┗ 📂js 222 | ┃ ┃ ┃ ┃ ┗ 📜app.js 223 | ┃ ┃ ┣ 📂templates 224 | ┃ ┃ ┃ ┣ 📂comment 225 | ┃ ┃ ┃ ┃ ┣ 📜form.mustache 226 | ┃ ┃ ┃ ┃ ┗ 📜list.mustache 227 | ┃ ┃ ┃ ┣ 📂layout 228 | ┃ ┃ ┃ ┃ ┣ 📜footer.mustache 229 | ┃ ┃ ┃ ┃ ┗ 📜header.mustache 230 | ┃ ┃ ┃ ┣ 📂posts 231 | ┃ ┃ ┃ ┃ ┣ 📜posts-page.mustache 232 | ┃ ┃ ┃ ┃ ┣ 📜posts-read.mustache 233 | ┃ ┃ ┃ ┃ ┣ 📜posts-search.mustache 234 | ┃ ┃ ┃ ┃ ┣ 📜posts-update.mustache 235 | ┃ ┃ ┃ ┃ ┗ 📜posts-write.mustache 236 | ┃ ┃ ┃ ┣ 📂user 237 | ┃ ┃ ┃ ┃ ┣ 📜user-join.mustache 238 | ┃ ┃ ┃ ┃ ┣ 📜user-login.mustache 239 | ┃ ┃ ┃ ┃ ┗ 📜user-modify.mustache 240 | ┃ ┃ ┃ ┗ 📜index.mustache 241 | ┃ ┃ ┣ 📜application-oauth.properties 242 | ┃ ┃ ┗ 📜application.properties 243 | ┗ 📂test 244 | ┃ ┗ 📂java 245 | ┃ ┃ ┗ 📂com 246 | ┃ ┃ ┃ ┗ 📂coco 247 | ┃ ┃ ┃ ┃ ┗ 📂board 248 | ┃ ┃ ┃ ┃ ┃ ┣ 📂controller 249 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜PostsApiControllerTest.java 250 | ┃ ┃ ┃ ┃ ┃ ┣ 📂domain 251 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜CommentRepositoryTest.java 252 | ┃ ┃ ┃ ┃ ┃ ┃ ┣ 📜PostsRepositoryTest.java 253 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜UserRepositoryTest.java 254 | ┃ ┃ ┃ ┃ ┃ ┣ 📂infrastructure 255 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📂config 256 | ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜SecurityConfigTest.java 257 | ┃ ┃ ┃ ┃ ┃ ┣ 📂service 258 | ┃ ┃ ┃ ┃ ┃ ┃ ┗ 📜PostsServiceTest.java 259 | ┃ ┃ ┃ ┃ ┃ ┗ 📜BoardApplicationTests.java 260 | ``` 261 | 262 |
263 |
264 | 265 | 266 | ### 2. DB 설계 267 | 268 | ![erd 3차 2022-01-03](https://user-images.githubusercontent.com/59757689/148910882-2ac9ec57-c339-4bef-a6d5-13025a8d9ac9.PNG) 269 | ![posts 테이블 db 설계](https://user-images.githubusercontent.com/59757689/148910938-c6a99c8e-fefc-467b-a2af-a68a00e01a11.PNG) 270 | ![user 테이블 db 설계](https://user-images.githubusercontent.com/59757689/149279956-b0a184da-9b19-4bcf-9ce8-6c001ef81f1d.PNG) 271 | ![comment 테이블 db 설계](https://user-images.githubusercontent.com/59757689/148910946-02280553-97ce-4d82-bbda-9c911ea89bd4.PNG) 272 | created_date와 modified_date는 날짜 포맷을 적용해주기 위해 datetime > varchar로 변경했습니다. 273 | 274 |
275 | 276 | ### 3. API 설계 277 | 278 | ![게시글 관련 API 설계](https://user-images.githubusercontent.com/59757689/156749365-5e4cee67-1431-4e3a-9140-7b58b6e1fd53.PNG) 279 | ![회원 관련 API 설계 (2)](https://user-images.githubusercontent.com/59757689/148911411-0cfb65ee-5782-4f04-a7c9-7dcc84abfed8.PNG) 280 | ![댓글 관련 API 설계v2](https://github.com/hojunnnnn/board/assets/59757689/fa9032f0-3ce1-4ec4-9dbd-f420fb4e6152) 281 | 282 | ## 개발 내용 283 | 284 | - 게시판 프로젝트 명세서 정리 285 | - 게시판 조회수 기능 추가 286 | - 게시판 페이징 처리 구현 287 | - 게시판 검색처리 및 페이징 구현 288 | - 생성, 수정시간 LocalDateTime format 변경 289 | - Security 회원가입 및 로그인 구현 290 | - Security Mustache CSRF 적용 및 문제해결 291 | - 커스텀 어노테이션을 통해 중복코드 개선 292 | - 회원가입 Validation 유효성 검사 293 | - 회원가입 Validation 커스터마이징 중복 검사 294 | - Security 로그인 실패시 메시지 출력하기 295 | - Security 회원정보 수정(ajax) 296 | - OAuth 2.0 구글 로그인 구현 297 | - OAuth 2.0 네이버 로그인 구현 298 | - JPA 연관관계 매핑으로 글 작성자만 수정, 삭제 가능하게 하기 299 | - JPA 양방향 순환참조 문제 및 해결 300 | - 게시판 댓글 작성 및 조회 구현 301 | - 게시판 댓글 수정 및 삭제 구현 302 | - 게시판 댓글 작성자만 수정, 삭제 가능하게 하기 303 | - [리팩토링]Dto Class를 Inner Class로 한번에 관리하기 304 | 305 | ## 마치며 306 | ### 1. 프로젝트 보완사항 307 | 308 | 초기에 구상한 기능은 기본적인 CRUD 즉, 게시판에 올라오는 게시글을 대상으로 Create, Read, Update, Delete가 가능한 게시판이었습니다. 309 | 템플릿 엔진으로 Mustache를 선택했는데, 그 이유는 Mustache는 단순히 화면에 데이터를 렌더링 하는 엔진이고 310 | Logic-less 하기 때문에 View의 역할과 서버의 역할이 명확하게 분리되어 OOP의 5원칙 중 하나인 SRP를 지킬 수 있어 311 | MVC 설계에서 Model, View, Controller의 역할에 대한 구분도 명확하게 할 수 있겠다는 생각이 들었습니다. 312 | 또한, 다른 템플릿에 비해 빠른 로딩 속도를 자랑하며, xss를 기본적으로 이스케이프 할 수 있다는 장점들에 이끌려 Mustache를 사용하게 되었습니다. 313 | 그러나 게시판 CRUD 기능이 완성되어 갈 때 쯤, 아쉬운 부분이 계속해서 생겨 몇몇 기능들을 추가하게 되었습니다. 314 | mustache는 로직을 넣을 수 없어 그 과정에 데이터를 렌더링 하기 전 서버에서 전처리를 하거나, 315 | 화면에 표시된 후에 자바스크립트로 후처리를 해줬지만 조금 아쉬운 부분이 몇 가지 남아있다고 생각합니다. 316 |
317 | 보완사항 318 | 319 | 320 | - 페이징 처리 및 검색 페이징에서 페이지 번호 활성화 321 | - 페이지 번호는 10페이지 단위로 보여주기 322 | - 페이지 처음, 끝으로 이동하는 버튼 323 | - 생성, 수정시간 format 설정 varchar > datetime 324 | - 다른 사용자와 자신의 댓글이 댓글란에 있을때 자신의 댓글만 수정,삭제 버튼 보이기 325 | 326 |
327 | 328 | 추후에 브랜치를 나눠 Mustache에서 Thymeleaf로 조금씩 바꾸며 프로젝트 완성도를 높이고, 고도화 할 계획에 있습니다. 329 | 330 |
331 | 추가할 기능 332 | 333 | 334 | - 댓글 페이징 처리 335 | - 쿠키나 세션을 이용해 조회수 중복 카운트 방지 336 | - 파일 업로드 기능 추가 337 | - 좋아요 기능 추가 338 | 339 |
340 | 341 | 342 | ### 2. 후기 343 | 344 | 혼자 독학하며 처음 만들어본 프로젝트이기 때문에, 345 | 공부한 내용을 사용해보는 설렘만큼이나 부족한 부분에 대한 아쉬움도 많이 남았습니다. 346 | 효율적인 설계를 위해 고민하고 찾아보며 실제로 많이 공부할 수 있었던 부분도 많았습니다. 347 | 책이나 블로그, 강의로 공부한 예제에서 납득했던 부분들은 실제로 코드를 짜면서 다양한 애로 사항을 마주했고 348 | '이 로직은 이 단계에서 처리하는게 맞는가', '각 레이어간 데이터 전달은 어떤 방식이든 DTO로 하는게 맞는가' 등 349 | 여러 고민에 빠져 헤맨적도 있었지만, 다행히 결과는 대부분 최선을 찾았었던 것 같습니다. 350 | 그리고 내가 만든 코드를 남에게 보여줬을 때, 누군가 코드의 근거를 물어본다면 351 | 과연 자신 있게 나의 생각을 잘 얘기할 수 있을까 라는 생각을 굉장히 많이 하게 되었습니다. 352 | 그래서 하나를 구현할 때 '이렇게 구현 하는 것이 과연 최선인가', '더 나은 Best Practice는 없을까' 353 | 스스로 의심하고 고민하게 되는 습관을 가지게 되었습니다. 354 | 355 | 두 번째로 기술적인 부분에서 더 공부하고 싶은 '방향'을 찾을 수 있었습니다. 356 | 이번 프로젝트는 저에게 좋은 경험이 되었고, 저의 부족한 부분을 스스로 알 수 있는 좋은 계기가 되었습니다. 357 | 부족한 부분에 대해 스스로 인지하고 있고, 더 깊게 공부하며 스스로 발전할 수 있는 '방향'을 다시한번 찾을 수 있게 되었습니다. 358 | 이를 통해 더 나은 웹 애플리케이션을 만들 수 있을 것 같다는 자신감도 생겼습니다. 359 | 360 | 끝까지 읽어주셔서 감사합니다. 361 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.5.6' 3 | id 'io.spring.dependency-management' version '1.0.11.RELEASE' 4 | id 'java' 5 | id 'war' 6 | } 7 | 8 | group = 'com.coco' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '11' 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom annotationProcessor 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | dependencies { 23 | implementation 'mysql:mysql-connector-java' 24 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 25 | implementation 'org.springframework.boot:spring-boot-starter-mustache' 26 | implementation 'org.springframework.boot:spring-boot-starter-web' 27 | implementation 'org.springframework.boot:spring-boot-starter-security' 28 | implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' 29 | implementation 'org.springframework.boot:spring-boot-starter-validation' 30 | compileOnly 'org.projectlombok:lombok' 31 | testCompileOnly 'org.projectlombok:lombok' 32 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 33 | annotationProcessor 'org.projectlombok:lombok' 34 | testAnnotationProcessor 'org.projectlombok:lombok' 35 | providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' 36 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 37 | } 38 | 39 | test { 40 | useJUnitPlatform() 41 | } 42 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hojunnnnn/board/938739b1f4d600e7f8d0140e8e0923050c4bd410/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'board' 2 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/BoardApplication.java: -------------------------------------------------------------------------------- 1 | package com.coco.board; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 7 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 8 | 9 | /** 추후 빌드 및 배포를 위해 SpringBootServletInitializer 상속 */ 10 | @SpringBootApplication 11 | @EnableJpaAuditing 12 | public class BoardApplication extends SpringBootServletInitializer { 13 | 14 | @Override 15 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 16 | return application.sources(BoardApplication.class); 17 | } 18 | 19 | public static void main(String[] args) { 20 | SpringApplication.run(BoardApplication.class, args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/CommentService.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application; 2 | 3 | import com.coco.board.application.dto.CommentDto; 4 | import com.coco.board.domain.Comment; 5 | import com.coco.board.infrastructure.persistence.CommentRepository; 6 | import com.coco.board.domain.Posts; 7 | import com.coco.board.infrastructure.persistence.PostsRepository; 8 | import com.coco.board.domain.User; 9 | import com.coco.board.infrastructure.persistence.UserRepository; 10 | import lombok.RequiredArgsConstructor; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | 17 | @RequiredArgsConstructor 18 | @Service 19 | public class CommentService { 20 | 21 | private final CommentRepository commentRepository; 22 | private final UserRepository userRepository; 23 | private final PostsRepository postsRepository; 24 | 25 | /* CREATE */ 26 | @Transactional 27 | public Long save(Long id, String nickname, CommentDto.Request dto) { 28 | User user = userRepository.findByNickname(nickname); 29 | Posts posts = postsRepository.findById(id).orElseThrow(() -> 30 | new IllegalArgumentException("댓글 쓰기 실패: 해당 게시글이 존재하지 않습니다. " + id)); 31 | 32 | dto.setUser(user); 33 | dto.setPosts(posts); 34 | 35 | Comment comment = dto.toEntity(); 36 | commentRepository.save(comment); 37 | 38 | return comment.getId(); 39 | } 40 | 41 | /* READ */ 42 | @Transactional(readOnly = true) 43 | public List findAll(Long id) { 44 | Posts posts = postsRepository.findById(id).orElseThrow(() -> 45 | new IllegalArgumentException("해당 게시글이 존재하지 않습니다. id: " + id)); 46 | List comments = posts.getComments(); 47 | return comments.stream().map(CommentDto.Response::new).collect(Collectors.toList()); 48 | } 49 | 50 | /* UPDATE */ 51 | @Transactional 52 | public void update(Long postsId, Long id, CommentDto.Request dto) { 53 | Comment comment = commentRepository.findByPostsIdAndId(postsId, id).orElseThrow(() -> 54 | new IllegalArgumentException("해당 댓글이 존재하지 않습니다. " + id)); 55 | 56 | comment.update(dto.getComment()); 57 | } 58 | 59 | /* DELETE */ 60 | @Transactional 61 | public void delete(Long postsId, Long id) { 62 | Comment comment = commentRepository.findByPostsIdAndId(postsId, id).orElseThrow(() -> 63 | new IllegalArgumentException("해당 댓글이 존재하지 않습니다. id=" + id)); 64 | 65 | commentRepository.delete(comment); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/PostsService.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application; 2 | 3 | import com.coco.board.application.dto.PostsDto; 4 | import com.coco.board.domain.Posts; 5 | import com.coco.board.infrastructure.persistence.PostsRepository; 6 | import com.coco.board.domain.User; 7 | import com.coco.board.infrastructure.persistence.UserRepository; 8 | import lombok.RequiredArgsConstructor; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.data.domain.Page; 11 | import org.springframework.data.domain.Pageable; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | @Slf4j 16 | @RequiredArgsConstructor 17 | @Service 18 | public class PostsService { 19 | 20 | private final PostsRepository postsRepository; 21 | private final UserRepository userRepository; 22 | 23 | /* CREATE */ 24 | @Transactional 25 | public Long save(PostsDto.Request dto, String nickname) { 26 | /* User 정보를 가져와 dto에 담아준다. */ 27 | User user = userRepository.findByNickname(nickname); 28 | dto.setUser(user); 29 | log.info("PostsService save() 실행"); 30 | Posts posts = dto.toEntity(); 31 | postsRepository.save(posts); 32 | 33 | return posts.getId(); 34 | } 35 | 36 | /* READ 게시글 리스트 조회 readOnly 속성으로 조회속도 개선 */ 37 | @Transactional(readOnly = true) 38 | public PostsDto.Response findById(Long id) { 39 | Posts posts = postsRepository.findById(id).orElseThrow(() -> 40 | new IllegalArgumentException("해당 게시글이 존재하지 않습니다. id: " + id)); 41 | 42 | return new PostsDto.Response(posts); 43 | } 44 | 45 | /* UPDATE (dirty checking 영속성 컨텍스트) 46 | * User 객체를 영속화시키고, 영속화된 User 객체를 가져와 데이터를 변경하면 47 | * 트랜잭션이 끝날 때 자동으로 DB에 저장해준다. */ 48 | @Transactional 49 | public void update(Long id, PostsDto.Request dto) { 50 | Posts posts = postsRepository.findById(id).orElseThrow(() -> 51 | new IllegalArgumentException("해당 게시글이 존재하지 않습니다. id=" + id)); 52 | 53 | posts.update(dto.getTitle(), dto.getContent()); 54 | } 55 | 56 | /* DELETE */ 57 | @Transactional 58 | public void delete(Long id) { 59 | Posts posts = postsRepository.findById(id).orElseThrow(() -> 60 | new IllegalArgumentException("해당 게시글이 존재하지 않습니다. id=" + id)); 61 | 62 | postsRepository.delete(posts); 63 | } 64 | 65 | /* Views Counting */ 66 | @Transactional 67 | public int updateView(Long id) { 68 | return postsRepository.updateView(id); 69 | } 70 | 71 | 72 | /* Paging and Sort */ 73 | @Transactional(readOnly = true) 74 | public Page pageList(Pageable pageable) { 75 | return postsRepository.findAll(pageable); 76 | } 77 | 78 | /* search */ 79 | @Transactional(readOnly = true) 80 | public Page search(String keyword, Pageable pageable) { 81 | Page postsList = postsRepository.findByTitleContaining(keyword, pageable); 82 | return postsList; 83 | } 84 | } 85 | 86 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/UserService.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application; 2 | 3 | import com.coco.board.domain.User; 4 | import com.coco.board.infrastructure.persistence.UserRepository; 5 | import com.coco.board.application.dto.UserDto; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | import org.springframework.validation.Errors; 11 | import org.springframework.validation.FieldError; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @RequiredArgsConstructor 17 | @Service 18 | public class UserService { 19 | 20 | private final UserRepository userRepository; 21 | 22 | private final BCryptPasswordEncoder encoder; 23 | 24 | /* 회원가입 */ 25 | @Transactional 26 | public void userJoin(UserDto.Request dto) { 27 | 28 | dto.setPassword(encoder.encode(dto.getPassword())); 29 | 30 | userRepository.save(dto.toEntity()); 31 | } 32 | 33 | /* 회원가입 시, 유효성 검사 및 중복 체크 */ 34 | @Transactional(readOnly = true) 35 | public Map validateHandling(Errors errors) { 36 | Map validatorResult = new HashMap<>(); 37 | 38 | /* 유효성 검사, 중복 검사에 실패한 필드 목록을 받음 */ 39 | for (FieldError error : errors.getFieldErrors()) { 40 | String validKeyName = String.format("valid_%s", error.getField()); 41 | validatorResult.put(validKeyName, error.getDefaultMessage()); 42 | } 43 | return validatorResult; 44 | } 45 | 46 | /* 회원수정 (dirty checking) */ 47 | @Transactional 48 | public void modify(UserDto.Request dto) { 49 | User user = userRepository.findById(dto.toEntity().getId()).orElseThrow(() -> 50 | new IllegalArgumentException("해당 회원이 존재하지 않습니다.")); 51 | 52 | String encPassword = encoder.encode(dto.getPassword()); 53 | user.modify(dto.getNickname(), encPassword); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/dto/CommentDto.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.dto; 2 | 3 | import com.coco.board.domain.Comment; 4 | import com.coco.board.domain.Posts; 5 | import com.coco.board.domain.User; 6 | import lombok.*; 7 | 8 | import java.time.LocalDateTime; 9 | import java.time.format.DateTimeFormatter; 10 | 11 | /** 12 | * request, response DTO 클래스를 하나로 묶어 InnerStaticClass로 한 번에 관리 13 | */ 14 | public class CommentDto { 15 | 16 | /** 댓글 Service 요청을 위한 DTO 클래스 */ 17 | @Data 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | @Builder 21 | public static class Request { 22 | private Long id; 23 | private String comment; 24 | private String createdDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm")); 25 | private String modifiedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm")); 26 | private User user; 27 | private Posts posts; 28 | /* Dto -> Entity */ 29 | public Comment toEntity() { 30 | Comment comments = Comment.builder() 31 | .id(id) 32 | .comment(comment) 33 | .createdDate(createdDate) 34 | .modifiedDate(modifiedDate) 35 | .user(user) 36 | .posts(posts) 37 | .build(); 38 | 39 | return comments; 40 | } 41 | } 42 | 43 | /** 44 | * 댓글 정보를 리턴할 응답(Response) 클래스 45 | * Entity 클래스를 생성자 파라미터로 받아 데이터를 Dto로 변환하여 응답 46 | * 별도의 전달 객체를 활용해 연관관계를 맺은 엔티티간의 무한참조를 방지 47 | */ 48 | @RequiredArgsConstructor 49 | @Getter 50 | public static class Response { 51 | private Long id; 52 | private String comment; 53 | private String createdDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm")); 54 | private String modifiedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm")); 55 | private String nickname; 56 | private Long userId; 57 | private Long postsId; 58 | /* Entity -> Dto*/ 59 | public Response(Comment comment) { 60 | this.id = comment.getId(); 61 | this.comment = comment.getComment(); 62 | this.createdDate = comment.getCreatedDate(); 63 | this.modifiedDate = comment.getModifiedDate(); 64 | this.nickname = comment.getUser().getNickname(); 65 | this.userId = comment.getUser().getId(); 66 | this.postsId = comment.getPosts().getId(); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/dto/PostsDto.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.dto; 2 | 3 | import com.coco.board.domain.Posts; 4 | import com.coco.board.domain.User; 5 | import lombok.*; 6 | 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | /** 11 | * request, response DTO 클래스를 하나로 묶어 InnerStaticClass로 한 번에 관리 12 | */ 13 | public class PostsDto { 14 | 15 | 16 | /** 게시글의 등록과 수정을 처리할 요청(Request) 클래스 */ 17 | @Data 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | @Builder 21 | public static class Request { 22 | 23 | private Long id; 24 | private String title; 25 | private String writer; 26 | private String content; 27 | private String createdDate, modifiedDate; 28 | private int view; 29 | private User user; 30 | 31 | /* Dto -> Entity */ 32 | public Posts toEntity() { 33 | Posts posts = Posts.builder() 34 | .id(id) 35 | .title(title) 36 | .writer(writer) 37 | .content(content) 38 | .view(0) 39 | .user(user) 40 | .build(); 41 | 42 | return posts; 43 | } 44 | } 45 | 46 | /** 47 | * 게시글 정보를 리턴할 응답(Response) 클래스 48 | * Entity 클래스를 생성자 파라미터로 받아 데이터를 Dto로 변환하여 응답 49 | * 별도의 전달 객체를 활용해 연관관계를 맺은 엔티티간의 무한참조를 방지 50 | */ 51 | @Getter 52 | public static class Response { 53 | private final Long id; 54 | private final String title; 55 | private final String writer; 56 | private final String content; 57 | private final String createdDate, modifiedDate; 58 | private final int view; 59 | private final Long userId; 60 | private final List comments; 61 | 62 | /* Entity -> Dto*/ 63 | public Response(Posts posts) { 64 | this.id = posts.getId(); 65 | this.title = posts.getTitle(); 66 | this.writer = posts.getWriter(); 67 | this.content = posts.getContent(); 68 | this.createdDate = posts.getCreatedDate(); 69 | this.modifiedDate = posts.getModifiedDate(); 70 | this.view = posts.getView(); 71 | this.userId = posts.getUser().getId(); 72 | this.comments = posts.getComments().stream().map(CommentDto.Response::new).collect(Collectors.toList()); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.dto; 2 | 3 | import com.coco.board.domain.Role; 4 | import com.coco.board.domain.User; 5 | import lombok.*; 6 | 7 | import javax.validation.constraints.NotBlank; 8 | import javax.validation.constraints.Pattern; 9 | import java.io.Serializable; 10 | 11 | /** 12 | * request, response DTO 클래스를 하나로 묶어 InnerStaticClass로 한 번에 관리 13 | */ 14 | public class UserDto { 15 | 16 | /** 회원 Service 요청(Request) DTO 클래스 */ 17 | @Data 18 | @AllArgsConstructor 19 | @NoArgsConstructor 20 | @Builder 21 | public static class Request { 22 | 23 | private Long id; 24 | 25 | @Pattern(regexp = "^[ㄱ-ㅎ가-힣a-z0-9-_]{4,20}$", message = "아이디는 특수문자를 제외한 4~20자리여야 합니다.") 26 | @NotBlank(message = "아이디는 필수 입력 값입니다.") 27 | private String username; 28 | 29 | @Pattern(regexp = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\\W)(?=\\S+$).{8,16}", message = "비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요.") 30 | private String password; 31 | 32 | @Pattern(regexp = "^[ㄱ-ㅎ가-힣a-zA-Z0-9-_]{2,10}$", message = "닉네임은 특수문자를 제외한 2~10자리여야 합니다.") 33 | @NotBlank(message = "닉네임은 필수 입력 값입니다.") 34 | private String nickname; 35 | 36 | @Pattern(regexp = "^(?:\\w+\\.?)*\\w+@(?:\\w+\\.)+\\w+$", message = "이메일 형식이 올바르지 않습니다.") 37 | @NotBlank(message = "이메일은 필수 입력 값입니다.") 38 | private String email; 39 | 40 | private Role role; 41 | 42 | /* DTO -> Entity */ 43 | public User toEntity() { 44 | User user = User.builder() 45 | .id(id) 46 | .username(username) 47 | .password(password) 48 | .nickname(nickname) 49 | .email(email) 50 | .role(role.USER) 51 | .build(); 52 | return user; 53 | } 54 | } 55 | 56 | /** 57 | * 인증된 사용자 정보를 세션에 저장하기 위한 클래스 58 | * 세션을 저장하기 위해 User 엔티티 클래스를 직접 사용하게 되면 직렬화를 해야 하는데, 59 | * 엔티티 클래스에 직렬화를 넣어주면 추후에 다른 엔티티와 연관관계를 맺을시 60 | * 직렬화 대상에 다른 엔티티까지 포함될 수 있어 성능 이슈 우려가 있기 때문에 61 | * 세션 저장용 Dto 클래스 생성 62 | * */ 63 | @Getter 64 | public static class Response implements Serializable { 65 | 66 | private final Long id; 67 | private final String username; 68 | private final String nickname; 69 | private final String email; 70 | private final Role role; 71 | private final String modifiedDate; 72 | 73 | /* Entity -> dto */ 74 | public Response(User user) { 75 | this.id = user.getId(); 76 | this.username = user.getUsername(); 77 | this.nickname = user.getNickname(); 78 | this.email = user.getEmail(); 79 | this.role = user.getRole(); 80 | this.modifiedDate = user.getModifiedDate(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/auth/CustomAuthFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.auth; 2 | 3 | import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; 4 | import org.springframework.security.authentication.BadCredentialsException; 5 | import org.springframework.security.authentication.InternalAuthenticationServiceException; 6 | import org.springframework.security.core.AuthenticationException; 7 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 8 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 9 | import org.springframework.stereotype.Component; 10 | 11 | import javax.servlet.ServletException; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import javax.servlet.http.HttpSession; 15 | import java.io.IOException; 16 | import java.net.URLEncoder; 17 | /** 18 | * 로그인 실패시 에러 메시지를 보여주기 위한 클래스 19 | */ 20 | @Component 21 | public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { 22 | 23 | private final HttpSession session; 24 | 25 | public CustomAuthFailureHandler(HttpSession session) { this.session = session; } 26 | 27 | @Override 28 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 29 | AuthenticationException exception) throws IOException, ServletException { 30 | String errorMessage; 31 | if (exception instanceof BadCredentialsException) { 32 | errorMessage = "아이디 또는 비밀번호가 일치하지 않습니다. 다시 확인해 주세요."; 33 | } else if (exception instanceof InternalAuthenticationServiceException) { 34 | errorMessage = "내부적으로 발생한 시스템 문제로 인해 요청을 처리할 수 없습니다. 관리자에게 문의하세요."; 35 | } else if (exception instanceof UsernameNotFoundException) { 36 | errorMessage = "계정이 존재하지 않습니다. 회원가입 진행 후 로그인 해주세요."; 37 | } else if (exception instanceof AuthenticationCredentialsNotFoundException) { 38 | errorMessage = "인증 요청이 거부되었습니다. 관리자에게 문의하세요."; 39 | } else { 40 | errorMessage = "알 수 없는 이유로 로그인에 실패하였습니다 관리자에게 문의하세요."; 41 | } 42 | 43 | /* 한글 자체는 url에 맞도록 자동으로 인코딩해주지 않기 때문에, 직접 UTF-8 인코딩 처리 */ 44 | errorMessage = URLEncoder.encode(errorMessage, "UTF-8"); 45 | 46 | setDefaultFailureUrl("/auth/login?error=true&exception="+errorMessage); 47 | 48 | super.onAuthenticationFailure(request, response, exception); 49 | 50 | session.invalidate(); // 세션 삭제 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/auth/CustomUserDetails.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.auth; 2 | 3 | import com.coco.board.domain.User; 4 | import lombok.AllArgsConstructor; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.ArrayList; 9 | import java.util.Collection; 10 | 11 | /** 12 | * 스프링 시큐리티가 로그인 요청을 가로채 로그인을 진행하고 완료 되면 UserDetails 타입의 오브젝트를 13 | * 스프링 시큐리티의 고유한 세션저장소에 저장 해준다. 14 | */ 15 | @AllArgsConstructor 16 | public class CustomUserDetails implements UserDetails { 17 | 18 | private final User user; 19 | 20 | @Override 21 | public String getPassword() { return user.getPassword(); } 22 | 23 | @Override 24 | public String getUsername() { 25 | return user.getUsername(); 26 | } 27 | 28 | /* 계정 만료 여부 29 | * true : 만료 안됨 30 | * false : 만료 31 | */ 32 | @Override 33 | public boolean isAccountNonExpired() { 34 | return true; 35 | } 36 | 37 | /* 계정 잠김 여부 38 | * true : 잠기지 않음 39 | * false : 잠김 40 | */ 41 | @Override 42 | public boolean isAccountNonLocked() { 43 | return true; 44 | } 45 | 46 | /* 비밀번호 만료 여부 47 | * true : 만료 안됨 48 | * false : 만료 49 | */ 50 | @Override 51 | public boolean isCredentialsNonExpired() { 52 | return true; 53 | } 54 | 55 | /* 사용자 활성화 여부 56 | * true : 만료 안됨 57 | * false : 만료 58 | */ 59 | @Override 60 | public boolean isEnabled() { 61 | return true; 62 | } 63 | 64 | /* 유저의 권한 목록 */ 65 | @Override 66 | public Collection getAuthorities() { 67 | Collection collectors = new ArrayList<>(); 68 | 69 | collectors.add(() -> "ROLE_"+user.getRole()); 70 | 71 | return collectors; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/auth/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.auth; 2 | 3 | import com.coco.board.domain.User; 4 | import com.coco.board.infrastructure.persistence.UserRepository; 5 | import com.coco.board.application.dto.UserDto; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | import org.springframework.stereotype.Service; 11 | 12 | import javax.servlet.http.HttpSession; 13 | 14 | /** 15 | * Security User Service 16 | */ 17 | @RequiredArgsConstructor 18 | @Service 19 | public class CustomUserDetailsService implements UserDetailsService { 20 | 21 | private final UserRepository userRepository; 22 | 23 | private final HttpSession session; 24 | 25 | /* username이 DB에 있는지 확인 */ 26 | @Override 27 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 28 | User user = userRepository.findByUsername(username).orElseThrow(() -> 29 | new UsernameNotFoundException("해당 사용자가 존재하지 않습니다. : " + username)); 30 | 31 | session.setAttribute("user", new UserDto.Response(user)); 32 | 33 | /* 시큐리티 세션에 유저 정보 저장 */ 34 | return new CustomUserDetails(user); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/auth/LoginUser.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.auth; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 세션 관련 중복코드 제거하기 위해 LoginUser 어노테이션 생성 10 | */ 11 | 12 | @Target(ElementType.PARAMETER) // 파라미터로 선언된 객체만 사용 13 | @Retention(RetentionPolicy.RUNTIME) //런타임까지 남아있는다. 14 | public @interface LoginUser { 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/auth/LoginUserArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.auth; 2 | 3 | import com.coco.board.application.dto.UserDto; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.core.MethodParameter; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.web.bind.support.WebDataBinderFactory; 8 | import org.springframework.web.context.request.NativeWebRequest; 9 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 10 | import org.springframework.web.method.support.ModelAndViewContainer; 11 | 12 | import javax.servlet.http.HttpSession; 13 | 14 | @RequiredArgsConstructor 15 | @Component 16 | public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver { 17 | 18 | private final HttpSession session; 19 | 20 | /* @LoginUser 어노테이션이 붙어 있고, 파라미터 클래스 타입이 UserDto.Response인가 판단 후 true반환 */ 21 | @Override 22 | public boolean supportsParameter(MethodParameter parameter) { 23 | boolean isLoginUserAnnotation = parameter.getParameterAnnotation(LoginUser.class) != null; 24 | 25 | boolean isUserClass = UserDto.Response.class.equals(parameter.getParameterType()); 26 | 27 | return isLoginUserAnnotation && isUserClass; 28 | } 29 | 30 | /* 파라미터에 전달할 객체 생성 */ 31 | @Override 32 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 33 | NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 34 | 35 | return session.getAttribute("user"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/oauth/CustomOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.oauth; 2 | 3 | import com.coco.board.domain.User; 4 | import com.coco.board.infrastructure.persistence.UserRepository; 5 | import com.coco.board.application.dto.UserDto; 6 | import lombok.RequiredArgsConstructor; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; 10 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 11 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; 12 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 13 | import org.springframework.security.oauth2.core.user.DefaultOAuth2User; 14 | import org.springframework.security.oauth2.core.user.OAuth2User; 15 | import org.springframework.stereotype.Service; 16 | 17 | import javax.servlet.http.HttpSession; 18 | import java.util.Collections; 19 | 20 | /** 21 | * Security UserDetailsService == OAuth OAuth2UserService 22 | * */ 23 | @Slf4j 24 | @RequiredArgsConstructor 25 | @Service 26 | public class CustomOAuth2UserService implements OAuth2UserService { 27 | 28 | private final UserRepository userRepository; 29 | private final HttpSession session; 30 | 31 | @Override 32 | public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { 33 | OAuth2UserService delegate = new DefaultOAuth2UserService(); 34 | OAuth2User oAuth2User = delegate.loadUser(userRequest); 35 | 36 | /* OAuth2 서비스 id 구분코드 ( 구글, 카카오, 네이버 ) */ 37 | String registrationId = userRequest.getClientRegistration().getRegistrationId(); 38 | 39 | log.info("registrationId : " + registrationId); 40 | 41 | /* OAuth2 로그인 진행시 키가 되는 필드 값 (PK) (구글의 기본 코드는 "sub") */ 42 | String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails() 43 | .getUserInfoEndpoint().getUserNameAttributeName(); 44 | 45 | log.info("============================================"); 46 | log.info("userNameAttributeName : " + userNameAttributeName); 47 | 48 | /* OAuth2UserService */ 49 | OAuthAttributes attributes = OAuthAttributes.of(registrationId, userNameAttributeName, oAuth2User.getAttributes()); 50 | log.info("============================================="); 51 | log.info("getAttributes(): " + attributes.getAttributes()); 52 | 53 | User user = saveOrUpdate(attributes); 54 | 55 | /* 세션 정보를 저장하는 직렬화된 dto 클래스 */ 56 | session.setAttribute("user", new UserDto.Response(user)); 57 | 58 | return new DefaultOAuth2User( 59 | Collections.singleton(new SimpleGrantedAuthority(user.getRoleValue())), 60 | attributes.getAttributes(), 61 | attributes.getNameAttributeKey()); 62 | } 63 | 64 | /* 소셜로그인시 기존 회원이 존재하면 수정날짜 정보만 업데이트해 기존의 데이터는 그대로 보존한다. */ 65 | private User saveOrUpdate(OAuthAttributes attributes) { 66 | User user = userRepository.findByEmail(attributes.getEmail()) 67 | .map(User::updateModifiedDate) 68 | .orElse(attributes.toEntity()); 69 | 70 | return userRepository.save(user); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/security/oauth/OAuthAttributes.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.security.oauth; 2 | 3 | import com.coco.board.domain.Role; 4 | import com.coco.board.domain.User; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Getter; 8 | import lombok.NoArgsConstructor; 9 | import lombok.extern.slf4j.Slf4j; 10 | 11 | import java.util.Map; 12 | 13 | /** 14 | * OAuth DTO Class 15 | */ 16 | @Slf4j 17 | @AllArgsConstructor 18 | @NoArgsConstructor 19 | @Builder 20 | @Getter 21 | public class OAuthAttributes { 22 | 23 | private Map attributes; 24 | private String nameAttributeKey; 25 | private String username; 26 | private String nickname; 27 | private String email; 28 | private Role role; 29 | 30 | public static OAuthAttributes of(String registrationId, String userNameAttributeName, 31 | Map attributes) { 32 | /* 구글인지 네이버인지 카카오인지 구분하기 위한 메소드 (ofNaver, ofKaKao) */ 33 | if ("naver".equals(registrationId)) { 34 | return ofNaver("id", attributes); 35 | } 36 | 37 | return ofGoogle(userNameAttributeName, attributes); 38 | } 39 | 40 | private static OAuthAttributes ofGoogle(String userNameAttributeName, 41 | Map attributes) { 42 | return OAuthAttributes.builder() 43 | .username((String) attributes.get("email")) 44 | .email((String) attributes.get("email")) 45 | .nickname((String) attributes.get("name")) 46 | .attributes(attributes) 47 | .nameAttributeKey(userNameAttributeName) 48 | .build(); 49 | } 50 | 51 | private static OAuthAttributes ofNaver(String userNameAttributeName, Map attributes) { 52 | /* JSON형태이기 때문에 Map을 통해 데이터를 가져온다. */ 53 | Map response = (Map) attributes.get("response"); 54 | 55 | log.info("naver response : " + response); 56 | 57 | return OAuthAttributes.builder() 58 | .username((String) response.get("email")) 59 | .email((String) response.get("email")) 60 | .nickname((String) response.get("nickname")) 61 | .attributes(response) 62 | .nameAttributeKey(userNameAttributeName) 63 | .build(); 64 | } 65 | 66 | public User toEntity() { 67 | return User.builder() 68 | .username(email) 69 | .email(email) 70 | .nickname(nickname) 71 | .role(Role.SOCIAL) 72 | .build(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/validator/AbstractValidator.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.validator; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.validation.Errors; 5 | import org.springframework.validation.Validator; 6 | 7 | /** 8 | * 중복검사 유효성 검증을 위해 Validator를 구현한 추상 클래스 9 | */ 10 | @Slf4j 11 | public abstract class AbstractValidator implements Validator { 12 | 13 | @Override 14 | public boolean supports(Class clazz) { 15 | return true; 16 | } 17 | 18 | @SuppressWarnings("unchecked") 19 | @Override 20 | public void validate(Object target, Errors errors) { 21 | try { 22 | doValidate((T) target, errors); 23 | } catch (IllegalStateException e) { 24 | log.error("중복 검증 에러", e); 25 | throw e; 26 | } 27 | } 28 | /* 유효성 검증 로직 */ 29 | protected abstract void doValidate(final T dto, final Errors errors); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/application/validator/CustomValidators.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.application.validator; 2 | 3 | import com.coco.board.application.dto.UserDto; 4 | import com.coco.board.infrastructure.persistence.UserRepository; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.stereotype.Component; 7 | import org.springframework.validation.Errors; 8 | 9 | /** 10 | * 중복 확인 유효성 검증을 위한 커스텀 Validator 클래스 11 | */ 12 | @RequiredArgsConstructor 13 | @Component 14 | public class CustomValidators { 15 | 16 | @RequiredArgsConstructor 17 | @Component 18 | public static class EmailValidator extends AbstractValidator { 19 | private final UserRepository userRepository; 20 | 21 | @Override 22 | protected void doValidate(UserDto.Request dto, Errors errors) { 23 | if (userRepository.existsByEmail(dto.toEntity().getEmail())) { 24 | errors.rejectValue("email", "이메일 중복 오류", "이미 사용중인 이메일 입니다."); 25 | } 26 | } 27 | } 28 | 29 | @RequiredArgsConstructor 30 | @Component 31 | public static class NicknameValidator extends AbstractValidator { 32 | private final UserRepository userRepository; 33 | 34 | @Override 35 | protected void doValidate(UserDto.Request dto, Errors errors) { 36 | if (userRepository.existsByNickname(dto.toEntity().getNickname())) { 37 | errors.rejectValue("nickname", "닉네임 중복 오류", "이미 사용중인 닉네임 입니다."); 38 | } 39 | } 40 | } 41 | 42 | @RequiredArgsConstructor 43 | @Component 44 | public static class UsernameValidator extends AbstractValidator { 45 | private final UserRepository userRepository; 46 | 47 | @Override 48 | protected void doValidate(UserDto.Request dto, Errors errors) { 49 | if (userRepository.existsByUsername(dto.toEntity().getUsername())) { 50 | errors.rejectValue("username", "아이디 중복 오류", "이미 사용중인 아이디 입니다."); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/domain/BaseTimeEntity.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import lombok.Getter; 4 | import org.springframework.data.annotation.CreatedDate; 5 | import org.springframework.data.annotation.LastModifiedDate; 6 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 7 | 8 | import javax.persistence.*; 9 | 10 | import java.time.LocalDate; 11 | import java.time.LocalDateTime; 12 | import java.time.format.DateTimeFormatter; 13 | 14 | /** 15 | * 공통적으로 사용되는 컬럼이므로, 이를 상속한 클래스에서 컬럼을 추가 16 | */ 17 | 18 | @Getter 19 | @MappedSuperclass 20 | @EntityListeners(AuditingEntityListener.class) 21 | abstract class BaseTimeEntity { 22 | 23 | @Column(name = "created_date", nullable = false) 24 | @CreatedDate 25 | private String createdDate; 26 | 27 | @Column(name = "modified_date", nullable = false) 28 | @LastModifiedDate 29 | private String modifiedDate; 30 | 31 | /* 해당 엔티티를 저장하기 이전에 실행 */ 32 | @PrePersist 33 | public void onPrePersist(){ 34 | this.createdDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd")); 35 | this.modifiedDate = this.createdDate; 36 | } 37 | 38 | /* 해당 엔티티를 업데이트 하기 이전에 실행*/ 39 | @PreUpdate 40 | public void onPreUpdate(){ 41 | this.modifiedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm")); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/coco/board/domain/Comment.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import org.springframework.data.annotation.CreatedDate; 8 | import org.springframework.data.annotation.LastModifiedDate; 9 | 10 | import javax.persistence.*; 11 | 12 | @Builder 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | @Getter 16 | @Table(name = "comments") 17 | @Entity 18 | public class Comment { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.IDENTITY) 22 | private Long id; 23 | 24 | @Column(columnDefinition = "TEXT", nullable = false) 25 | private String comment; // 댓글 내용 26 | 27 | @Column(name = "created_date") 28 | @CreatedDate 29 | private String createdDate; 30 | 31 | @Column(name = "modified_date") 32 | @LastModifiedDate 33 | private String modifiedDate; 34 | 35 | @ManyToOne 36 | @JoinColumn(name = "posts_id") 37 | private Posts posts; 38 | 39 | @ManyToOne 40 | @JoinColumn(name = "user_id") 41 | private User user; // 작성자 42 | 43 | /* 댓글 수정 */ 44 | public void update(String comment) { 45 | this.comment = comment; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/domain/Posts.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | import java.util.List; 7 | 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | @Builder 11 | @Getter 12 | @Entity 13 | public class Posts extends BaseTimeEntity { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id; 18 | 19 | @Column(length = 500, nullable = false) 20 | private String title; 21 | 22 | @Column(columnDefinition = "TEXT", nullable = false) 23 | private String content; 24 | 25 | @Column(nullable = false) 26 | private String writer; 27 | 28 | @Column(columnDefinition = "integer default 0", nullable = false) 29 | private int view; 30 | 31 | @ManyToOne(fetch = FetchType.LAZY) 32 | @JoinColumn(name = "user_id") 33 | private User user; 34 | 35 | @OneToMany(mappedBy = "posts", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE) 36 | @OrderBy("id asc") // 댓글 정렬 37 | private List comments; 38 | 39 | /* 게시글 수정 */ 40 | public void update(String title, String content) { 41 | this.title = title; 42 | this.content = content; 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/java/com/coco/board/domain/Role.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @Getter 7 | @RequiredArgsConstructor 8 | public enum Role { 9 | USER("ROLE_USER"), 10 | ADMIN("ROLE_ADMIN"), 11 | SOCIAL("ROLE_SOCIAL"); 12 | 13 | private final String value; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import lombok.*; 4 | 5 | import javax.persistence.*; 6 | 7 | @AllArgsConstructor 8 | @NoArgsConstructor 9 | @Builder 10 | @Getter 11 | @Entity 12 | public class User extends BaseTimeEntity { 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Long id; 17 | 18 | @Column(nullable = false, length = 30, unique = true) 19 | private String username; // 아이디 20 | 21 | @Column(nullable = false, unique = true) 22 | private String nickname; 23 | 24 | @Column(length = 100) 25 | private String password; 26 | 27 | @Column(nullable = false, length = 50, unique = true) 28 | private String email; 29 | 30 | @Enumerated(EnumType.STRING) 31 | @Column(nullable = false) 32 | private Role role; 33 | 34 | /* 회원정보 수정 */ 35 | public void modify(String nickname, String password) { 36 | this.nickname = nickname; 37 | this.password = password; 38 | } 39 | 40 | /* 소셜로그인시 이미 등록된 회원이라면 수정날짜만 업데이트해줘서 41 | * 기존 데이터를 보존하도록 예외처리 */ 42 | public User updateModifiedDate() { 43 | this.onPreUpdate(); 44 | return this; 45 | } 46 | 47 | public String getRoleValue() { 48 | return this.role.getValue(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/infrastructure/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.config; 2 | 3 | import com.coco.board.application.security.oauth.CustomOAuth2UserService; 4 | import com.coco.board.application.security.auth.CustomUserDetailsService; 5 | 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 11 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 13 | import org.springframework.security.config.annotation.web.builders.WebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 16 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 17 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 18 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 19 | 20 | /** 21 | * Security 설정 클래스 22 | */ 23 | @RequiredArgsConstructor 24 | @Configuration 25 | @EnableWebSecurity 26 | @EnableGlobalMethodSecurity(prePostEnabled = true) // 특정 주소로 접근하면 권한 및 인증을 미리 체크 27 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 28 | 29 | private final CustomUserDetailsService customUserDetailsService; 30 | 31 | private final AuthenticationFailureHandler customFailureHandler; 32 | 33 | private final CustomOAuth2UserService customOAuth2UserService; 34 | 35 | @Bean 36 | public BCryptPasswordEncoder encoder() { 37 | return new BCryptPasswordEncoder(); 38 | } 39 | 40 | @Bean 41 | @Override 42 | public AuthenticationManager authenticationManagerBean() throws Exception { 43 | return super.authenticationManagerBean(); 44 | } 45 | 46 | /* 시큐리티가 로그인 과정에서 password를 가로챌때 어떤 해쉬로 암호화 했는지 확인 */ 47 | @Override 48 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 49 | auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder()); 50 | } 51 | 52 | /* static 관련설정은 무시 */ 53 | @Override 54 | public void configure(WebSecurity web) throws Exception { 55 | web 56 | .ignoring().antMatchers( "/css/**", "/js/**", "/img/**"); 57 | } 58 | 59 | @Override 60 | protected void configure(HttpSecurity http) throws Exception { 61 | http 62 | .csrf().ignoringAntMatchers("/api/**") /* REST API 사용 예외처리 */ 63 | .and() 64 | .authorizeRequests() 65 | .antMatchers("/", "/auth/**", "/posts/read/**", "/posts/search/**").permitAll() 66 | .anyRequest().authenticated() 67 | .and() 68 | .formLogin() 69 | .loginPage("/auth/login") 70 | .loginProcessingUrl("/auth/loginProc") 71 | .failureHandler(customFailureHandler) 72 | .defaultSuccessUrl("/") 73 | .and() 74 | .logout() 75 | .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 76 | .invalidateHttpSession(true).deleteCookies("JSESSIONID") 77 | .logoutSuccessUrl("/") 78 | .and() 79 | .oauth2Login() 80 | .userInfoEndpoint() // OAuth2 로그인 성공 후 가져올 설정들 81 | .userService(customOAuth2UserService); // 서버에서 사용자 정보를 가져온 상태에서 추가로 진행하고자 하는 기능 명시 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/infrastructure/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.config; 2 | 3 | import com.coco.board.application.security.auth.LoginUserArgumentResolver; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | import java.util.List; 10 | /** 11 | * LoginUserArgumentResolver가 인식될 수 있도록 WebMvcConfigurer에 추가 12 | */ 13 | @RequiredArgsConstructor 14 | @Configuration 15 | public class WebConfig implements WebMvcConfigurer { 16 | 17 | private final LoginUserArgumentResolver loginUserArgumentResolver; 18 | 19 | /* HandlerMethodArgumentResolver는 항상 addArgumentResolvers()를 통해 추가해야 함 */ 20 | @Override 21 | public void addArgumentResolvers(List resolvers) { 22 | resolvers.add(loginUserArgumentResolver); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/infrastructure/persistence/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.persistence; 2 | 3 | import com.coco.board.domain.Comment; 4 | import com.coco.board.domain.Posts; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | public interface CommentRepository extends JpaRepository { 11 | /* 게시글 댓글 목록 가져오기 */ 12 | List getCommentByPostsOrderById(Posts posts); 13 | 14 | Optional findByPostsIdAndId(Long postsId, Long id); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/infrastructure/persistence/PostsRepository.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.persistence; 2 | 3 | import com.coco.board.domain.Posts; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.data.jpa.repository.Modifying; 8 | import org.springframework.data.jpa.repository.Query; 9 | 10 | public interface PostsRepository extends JpaRepository { 11 | @Modifying 12 | @Query("update Posts p set p.view = p.view + 1 where p.id = :id") 13 | int updateView(Long id); 14 | 15 | Page findByTitleContaining(String keyword, Pageable pageable); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/infrastructure/persistence/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.persistence; 2 | 3 | import com.coco.board.domain.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserRepository extends JpaRepository { 9 | /* Security */ 10 | Optional findByUsername(String username); 11 | 12 | /* OAuth */ 13 | Optional findByEmail(String email); 14 | 15 | /* user GET */ 16 | User findByNickname(String nickname); 17 | 18 | /* 중복 검사> 중복인 경우 true, 중복되지 않은경우 false 리턴 */ 19 | boolean existsByUsername(String username); 20 | boolean existsByNickname(String nickname); 21 | boolean existsByEmail(String email); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/presentation/CommentApiController.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.presentation; 2 | 3 | import com.coco.board.application.security.auth.LoginUser; 4 | import com.coco.board.application.CommentService; 5 | import com.coco.board.application.dto.CommentDto; 6 | import com.coco.board.application.dto.UserDto; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * REST API Controller 15 | */ 16 | @RequiredArgsConstructor 17 | @RequestMapping("/api") 18 | @RestController 19 | public class CommentApiController { 20 | 21 | private final CommentService commentService; 22 | 23 | /* CREATE */ 24 | @PostMapping("/posts/{id}/comments") 25 | public ResponseEntity save(@PathVariable Long id, @RequestBody CommentDto.Request dto, 26 | @LoginUser UserDto.Response userSessionDto) { 27 | return ResponseEntity.ok(commentService.save(id, userSessionDto.getNickname(), dto)); 28 | } 29 | 30 | /* READ */ 31 | @GetMapping("/posts/{id}/comments") 32 | public List read(@PathVariable Long id) { 33 | return commentService.findAll(id); 34 | } 35 | 36 | /* UPDATE */ 37 | @PutMapping({"/posts/{postsId}/comments/{id}"}) 38 | public ResponseEntity update(@PathVariable Long postsId, @PathVariable Long id, @RequestBody CommentDto.Request dto) { 39 | commentService.update(postsId, id, dto); 40 | return ResponseEntity.ok(id); 41 | } 42 | 43 | /* DELETE */ 44 | @DeleteMapping("/posts/{postsId}/comments/{id}") 45 | public ResponseEntity delete(@PathVariable Long postsId, @PathVariable Long id) { 46 | commentService.delete(postsId, id); 47 | return ResponseEntity.ok(id); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/presentation/PostsApiController.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.presentation; 2 | 3 | import com.coco.board.application.security.auth.LoginUser; 4 | import com.coco.board.application.PostsService; 5 | import com.coco.board.application.dto.PostsDto; 6 | import com.coco.board.application.dto.UserDto; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | /** 12 | * REST API Controller 13 | */ 14 | @RequestMapping("/api") 15 | @RequiredArgsConstructor 16 | @RestController 17 | public class PostsApiController { 18 | 19 | private final PostsService postsService; 20 | 21 | /* CREATE */ 22 | @PostMapping("/posts") 23 | public ResponseEntity save(@RequestBody PostsDto.Request dto, @LoginUser UserDto.Response user) { 24 | return ResponseEntity.ok(postsService.save(dto, user.getNickname())); 25 | } 26 | 27 | /* READ */ 28 | @GetMapping("/posts/{id}") 29 | public ResponseEntity read(@PathVariable Long id) { 30 | return ResponseEntity.ok(postsService.findById(id)); 31 | } 32 | 33 | /* UPDATE */ 34 | @PutMapping("/posts/{id}") 35 | public ResponseEntity update(@PathVariable Long id, @RequestBody PostsDto.Request dto) { 36 | postsService.update(id, dto); 37 | return ResponseEntity.ok(id); 38 | } 39 | 40 | /* DELETE */ 41 | @DeleteMapping("/posts/{id}") 42 | public ResponseEntity delete(@PathVariable Long id) { 43 | postsService.delete(id); 44 | return ResponseEntity.ok(id); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/presentation/PostsIndexController.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.presentation; 2 | 3 | import com.coco.board.application.security.auth.LoginUser; 4 | import com.coco.board.application.dto.CommentDto; 5 | import com.coco.board.application.dto.PostsDto; 6 | import com.coco.board.application.dto.UserDto; 7 | import com.coco.board.domain.Posts; 8 | import com.coco.board.application.PostsService; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.data.domain.Page; 12 | import org.springframework.data.domain.Pageable; 13 | import org.springframework.data.domain.Sort; 14 | import org.springframework.data.web.PageableDefault; 15 | import org.springframework.stereotype.Controller; 16 | import org.springframework.ui.Model; 17 | import org.springframework.web.bind.annotation.GetMapping; 18 | import org.springframework.web.bind.annotation.PathVariable; 19 | 20 | import java.util.List; 21 | 22 | /** 23 | * 화면 연결 Controller 24 | */ 25 | @Slf4j 26 | @RequiredArgsConstructor 27 | @Controller 28 | public class PostsIndexController { 29 | 30 | private final PostsService postsService; 31 | 32 | @GetMapping("/") /* default page = 0, size = 10 */ 33 | public String index(Model model, @PageableDefault(sort = "id", direction = Sort.Direction.DESC) 34 | Pageable pageable, @LoginUser UserDto.Response user) { 35 | Page list = postsService.pageList(pageable); 36 | 37 | if (user != null) { 38 | model.addAttribute("user", user); 39 | } 40 | 41 | model.addAttribute("posts", list); 42 | model.addAttribute("previous", pageable.previousOrFirst().getPageNumber()); 43 | model.addAttribute("next", pageable.next().getPageNumber()); 44 | model.addAttribute("hasNext", list.hasNext()); 45 | model.addAttribute("hasPrev", list.hasPrevious()); 46 | 47 | return "index"; 48 | } 49 | /* 글 작성 */ 50 | @GetMapping("/posts/write") 51 | public String write(@LoginUser UserDto.Response user, Model model) { 52 | if (user != null) { 53 | model.addAttribute("user", user); 54 | } 55 | return "posts/posts-write"; 56 | } 57 | 58 | /* 글 상세보기 */ 59 | @GetMapping("/posts/read/{id}") 60 | public String read(@PathVariable Long id, @LoginUser UserDto.Response user, Model model) { 61 | PostsDto.Response dto = postsService.findById(id); 62 | List comments = dto.getComments(); 63 | 64 | 65 | /* 댓글 관련 */ 66 | if (comments != null && !comments.isEmpty()) { 67 | model.addAttribute("comments", comments); 68 | } 69 | 70 | /* 사용자 관련 */ 71 | if (user != null) { 72 | model.addAttribute("user", user); 73 | 74 | /* 게시글 작성자 본인인지 확인 */ 75 | if (dto.getUserId().equals(user.getId())) { 76 | model.addAttribute("writer", true); 77 | } 78 | 79 | /* 댓글 작성자 본인인지 확인 */ 80 | if (comments.stream().anyMatch(s -> s.getUserId().equals(user.getId()))) { 81 | model.addAttribute("isWriter", true); 82 | } 83 | /* for (int i = 0; i < comments.size(); i++) { 84 | boolean isWriter = comments.get(i).getUserId().equals(user.getId()); 85 | model.addAttribute("isWriter",isWriter); 86 | }*/ 87 | } 88 | 89 | postsService.updateView(id); // views ++ 90 | model.addAttribute("posts", dto); 91 | return "posts/posts-read"; 92 | } 93 | 94 | @GetMapping("/posts/update/{id}") 95 | public String update(@PathVariable Long id, @LoginUser UserDto.Response user, Model model) { 96 | PostsDto.Response dto = postsService.findById(id); 97 | if (user != null) { 98 | model.addAttribute("user", user); 99 | } 100 | model.addAttribute("posts", dto); 101 | 102 | return "posts/posts-update"; 103 | } 104 | 105 | @GetMapping("/posts/search") 106 | public String search(String keyword, Model model, @PageableDefault(sort = "id", direction = Sort.Direction.DESC) 107 | Pageable pageable, @LoginUser UserDto.Response user) { 108 | Page searchList = postsService.search(keyword, pageable); 109 | 110 | if (user != null) { 111 | model.addAttribute("user", user); 112 | } 113 | model.addAttribute("searchList", searchList); 114 | model.addAttribute("keyword", keyword); 115 | model.addAttribute("previous", pageable.previousOrFirst().getPageNumber()); 116 | model.addAttribute("next", pageable.next().getPageNumber()); 117 | model.addAttribute("hasNext", searchList.hasNext()); 118 | model.addAttribute("hasPrev", searchList.hasPrevious()); 119 | 120 | return "posts/posts-search"; 121 | } 122 | } 123 | 124 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/presentation/UserApiController.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.presentation; 2 | 3 | import com.coco.board.application.UserService; 4 | import com.coco.board.application.dto.UserDto; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.context.SecurityContextHolder; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | /** 19 | * REST API Controller 20 | */ 21 | @RequiredArgsConstructor 22 | @RequestMapping("/api") 23 | @RestController 24 | public class UserApiController { 25 | 26 | private final UserService userService; 27 | 28 | private final AuthenticationManager authenticationManager; 29 | 30 | @PutMapping("/user") 31 | public ResponseEntity modify(@RequestBody UserDto.Request dto) { 32 | userService.modify(dto); 33 | 34 | /* 변경된 세션 등록 */ 35 | Authentication authentication = authenticationManager.authenticate( 36 | new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword())); 37 | 38 | SecurityContextHolder.getContext().setAuthentication(authentication); 39 | 40 | return new ResponseEntity<>("success", HttpStatus.OK); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/coco/board/presentation/UserController.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.presentation; 2 | 3 | import com.coco.board.application.security.auth.LoginUser; 4 | import com.coco.board.application.UserService; 5 | import com.coco.board.application.dto.UserDto; 6 | import com.coco.board.application.validator.CustomValidators; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; 11 | import org.springframework.stereotype.Controller; 12 | import org.springframework.ui.Model; 13 | import org.springframework.validation.Errors; 14 | import org.springframework.web.bind.WebDataBinder; 15 | import org.springframework.web.bind.annotation.GetMapping; 16 | import org.springframework.web.bind.annotation.InitBinder; 17 | import org.springframework.web.bind.annotation.PostMapping; 18 | import org.springframework.web.bind.annotation.RequestParam; 19 | 20 | import javax.servlet.http.HttpServletRequest; 21 | import javax.servlet.http.HttpServletResponse; 22 | import javax.validation.Valid; 23 | import java.util.Map; 24 | 25 | /** 26 | * 회원 관련 Controller 27 | */ 28 | @RequiredArgsConstructor 29 | @Controller 30 | public class UserController { 31 | 32 | private final UserService userService; 33 | 34 | private final CustomValidators.EmailValidator EmailValidator; 35 | private final CustomValidators.NicknameValidator NicknameValidator; 36 | private final CustomValidators.UsernameValidator UsernameValidator; 37 | 38 | /* 커스텀 유효성 검증을 위해 추가 */ 39 | @InitBinder 40 | public void validatorBinder(WebDataBinder binder) { 41 | binder.addValidators(EmailValidator); 42 | binder.addValidators(NicknameValidator); 43 | binder.addValidators(UsernameValidator); 44 | } 45 | 46 | @GetMapping("/auth/join") 47 | public String join() { 48 | return "/user/user-join"; 49 | } 50 | 51 | /* 회원가입 */ 52 | @PostMapping("/auth/joinProc") 53 | public String joinProc(@Valid UserDto.Request dto, Errors errors, Model model) { 54 | if (errors.hasErrors()) { 55 | /* 회원가입 실패시 입력 데이터 값을 유지 */ 56 | model.addAttribute("userDto", dto); 57 | 58 | /* 유효성 통과 못한 필드와 메시지를 핸들링 */ 59 | Map validatorResult = userService.validateHandling(errors); 60 | for (String key : validatorResult.keySet()) { 61 | model.addAttribute(key, validatorResult.get(key)); 62 | } 63 | /* 회원가입 페이지로 다시 리턴 */ 64 | return "/user/user-join"; 65 | } 66 | userService.userJoin(dto); 67 | return "redirect:/auth/login"; 68 | } 69 | 70 | @GetMapping("/auth/login") 71 | public String login(@RequestParam(value = "error", required = false)String error, 72 | @RequestParam(value = "exception", required = false)String exception, 73 | Model model) { 74 | model.addAttribute("error", error); 75 | model.addAttribute("exception", exception); 76 | return "/user/user-login"; 77 | } 78 | 79 | /* Security에서 로그아웃은 기본적으로 POST지만, GET으로 우회 */ 80 | @GetMapping("/logout") 81 | public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception { 82 | 83 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 84 | if (auth != null) { 85 | new SecurityContextLogoutHandler().logout(request, response, auth); 86 | } 87 | return "redirect:/"; 88 | } 89 | 90 | /* 회원정보 수정 */ 91 | @GetMapping("/modify") 92 | public String modify(@LoginUser UserDto.Response user, Model model) { 93 | if (user != null) { 94 | model.addAttribute("user", user); 95 | } 96 | return "/user/user-modify"; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # MYSQL DATABASE SETTING 2 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 3 | spring.datasource.url=jdbc:mysql://localhost:3306/coco?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul 4 | spring.datasource.username=coco 5 | spring.datasource.password= 6 | 7 | spring.jpa.show-sql=true 8 | spring.jpa.hibernate.ddl-auto=update 9 | spring.jpa.properties.hibernate.format_sql=true 10 | 11 | # MUSTACHE 12 | spring.mustache.expose-request-attributes=true 13 | 14 | # OAUTH 15 | spring.profiles.include=oauth -------------------------------------------------------------------------------- /src/main/resources/static/css/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | height: 150%; 3 | padding: 0; 4 | margin: 0; 5 | } 6 | 7 | input:invalid { 8 | border-color: red; 9 | } 10 | #header { 11 | background: #69cdaa; 12 | color: #ffffff; 13 | padding: 25px; 14 | font-size: 4em; 15 | } 16 | #header a:link { color:#ffffff; text-decoration: none;} 17 | 18 | #header a:visited { color:#ffffff; text-decoration: none;} 19 | 20 | #header a:hover { color:#ffffff; text-decoration: none;} 21 | 22 | #header a:active { color:#ffffff; text-decoration: none;} 23 | 24 | 25 | #footer { 26 | position: fixed; 27 | width: 100%; 28 | height: 50px; 29 | background-color:#363636; 30 | bottom: 0; 31 | left: 0; 32 | color:#ffffff; 33 | text-align:center; 34 | line-height:50px; 35 | 36 | } 37 | #footer a:link { color:#ffffff; text-decoration: none;} 38 | 39 | #footer a:visited { color:#ffffff; text-decoration: none;} 40 | 41 | #footer a:hover { color:#ffffff; text-decoration: none;} 42 | 43 | #footer a:active { color:#ffffff; text-decoration: none;} 44 | 45 | 46 | #nav { 47 | background: #f5f5f5; 48 | padding: 12px; 49 | border-top: 2px solid gainsboro; 50 | border-bottom: 2px; 51 | } 52 | 53 | #posts_list { 54 | position: relative; 55 | min-height: 100%; 56 | width: 100%; 57 | max-width: 1100px; 58 | margin: 0 auto 20px auto; 59 | } 60 | 61 | #table { 62 | border-bottom: 2px solid gainsboro; 63 | } 64 | #thead { 65 | background: #434343; 66 | color: #ffffff; 67 | } 68 | 69 | #valid { 70 | font-size: xx-small; 71 | color: red; 72 | } 73 | 74 | #img { width: 20px; height: auto; padding-bottom: 4px; } 75 | 76 | 77 | -------------------------------------------------------------------------------- /src/main/resources/static/img/naver.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hojunnnnn/board/938739b1f4d600e7f8d0140e8e0923050c4bd410/src/main/resources/static/img/naver.ico -------------------------------------------------------------------------------- /src/main/resources/static/js/app.js: -------------------------------------------------------------------------------- 1 | const main = { 2 | init : function() { 3 | const _this = this; 4 | 5 | // 게시글 저장 6 | $('#btn-save').on('click', function () { 7 | _this.save(); 8 | }); 9 | // 게시글 수정 10 | $('#btn-update').on('click', function () { 11 | _this.update(); 12 | }); 13 | // 게시글 삭제 14 | $('#btn-delete').on('click', function () { 15 | _this.delete(); 16 | }); 17 | 18 | // 회원 수정 19 | $('#btn-user-modify').on('click', function () { 20 | _this.userModify(); 21 | }); 22 | 23 | // 댓글 저장 24 | $('#btn-comment-save').on('click', function () { 25 | _this.commentSave(); 26 | }); 27 | // 댓글 수정 28 | document.querySelectorAll('#btn-comment-update').forEach(function (item) { 29 | item.addEventListener('click', function () { // 버튼 클릭 이벤트 발생시 30 | const form = this.closest('form'); // btn의 가장 가까운 조상의 Element(form)를 반환 (closest) 31 | _this.commentUpdate(form); // 해당 폼으로 업데이트 수행 32 | }); 33 | }); 34 | }, 35 | 36 | /** 글 작성 */ 37 | save : function () { 38 | const data = { 39 | title: $('#title').val(), 40 | writer: $('#writer').val(), 41 | content: $('#content').val() 42 | }; 43 | // 공백 및 빈 문자열 체크 44 | if (!data.title || data.title.trim() === "" || !data.content || data.content.trim() === "") { 45 | alert("공백 또는 입력하지 않은 부분이 있습니다."); 46 | return false; 47 | } else { 48 | $.ajax({ 49 | type: 'POST', 50 | url: '/api/posts', 51 | dataType: 'JSON', 52 | contentType: 'application/json; charset=utf-8', 53 | data: JSON.stringify(data) 54 | }).done(function () { 55 | alert('등록되었습니다.'); 56 | window.location.href = '/'; 57 | }).fail(function (error) { 58 | alert(JSON.stringify(error)); 59 | }); 60 | } 61 | }, 62 | 63 | /** 글 수정 */ 64 | update : function () { 65 | const data = { 66 | id: $('#id').val(), 67 | title: $('#title').val(), 68 | content: $('#content').val() 69 | }; 70 | 71 | const con_check = confirm("수정하시겠습니까?"); 72 | if (con_check === true) { 73 | if (!data.title || data.title.trim() === "" || !data.content || data.content.trim() === "") { 74 | alert("공백 또는 입력하지 않은 부분이 있습니다."); 75 | return false; 76 | } else { 77 | $.ajax({ 78 | type: 'PUT', 79 | url: '/api/posts/' + data.id, 80 | dataType: 'JSON', 81 | contentType: 'application/json; charset=utf-8', 82 | data: JSON.stringify(data) 83 | }).done(function () { 84 | alert("수정되었습니다."); 85 | window.location.href = '/posts/read/' + data.id; 86 | }).fail(function (error) { 87 | alert(JSON.stringify(error)); 88 | }); 89 | } 90 | } 91 | }, 92 | 93 | /** 글 삭제 */ 94 | delete : function () { 95 | const id = $('#id').val(); 96 | const con_check = confirm("정말 삭제하시겠습니까?"); 97 | 98 | if(con_check == true) { 99 | $.ajax({ 100 | type: 'DELETE', 101 | url: '/api/posts/'+id, 102 | dataType: 'JSON', 103 | contentType: 'application/json; charset=utf-8' 104 | 105 | }).done(function () { 106 | alert("삭제되었습니다."); 107 | window.location.href = '/'; 108 | }).fail(function (error) { 109 | alert(JSON.stringify(error)); 110 | }); 111 | } else { 112 | return false; 113 | } 114 | }, 115 | 116 | /** 회원 수정 */ 117 | userModify : function () { 118 | const data = { 119 | id: $('#id').val(), 120 | modifiedDate: $('#modifiedDate').val(), 121 | username: $('#username').val(), 122 | nickname: $('#nickname').val(), 123 | password: $('#password').val() 124 | } 125 | if(!data.nickname || data.nickname.trim() === "" || !data.password || data.password.trim() === "") { 126 | alert("공백 또는 입력하지 않은 부분이 있습니다."); 127 | return false; 128 | } else if(!/(?=.*[0-9])(?=.*[a-zA-Z])(?=.*\W)(?=\S+$).{8,16}/.test(data.password)) { 129 | alert("비밀번호는 8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요."); 130 | $('#password').focus(); 131 | return false; 132 | } else if(!/^[ㄱ-ㅎ가-힣a-zA-Z0-9-_]{2,10}$/.test(data.nickname)) { 133 | alert("닉네임은 특수문자를 제외한 2~10자리여야 합니다."); 134 | $('#nickname').focus(); 135 | return false; 136 | } 137 | const con_check = confirm("수정하시겠습니까?"); 138 | if (con_check === true) { 139 | $.ajax({ 140 | type: "PUT", 141 | url: "/api/user", 142 | contentType: 'application/json; charset=utf-8', 143 | data: JSON.stringify(data) 144 | 145 | }).done(function () { 146 | alert("회원수정이 완료되었습니다."); 147 | window.location.href = "/"; 148 | 149 | }).fail(function (error) { 150 | if (error.status === 500) { 151 | alert("이미 사용중인 닉네임 입니다."); 152 | $('#nickname').focus(); 153 | } else { 154 | alert(JSON.stringify(error)); 155 | } 156 | }); 157 | } else { 158 | return false; 159 | } 160 | }, 161 | 162 | /** 댓글 저장 */ 163 | commentSave : function () { 164 | const data = { 165 | postsId: $('#postsId').val(), 166 | comment: $('#comment').val() 167 | } 168 | 169 | // 공백 및 빈 문자열 체크 170 | if (!data.comment || data.comment.trim() === "") { 171 | alert("공백 또는 입력하지 않은 부분이 있습니다."); 172 | return false; 173 | } else { 174 | $.ajax({ 175 | type: 'POST', 176 | url: '/api/posts/' + data.postsId + '/comments', 177 | dataType: 'JSON', 178 | contentType: 'application/json; charset=utf-8', 179 | data: JSON.stringify(data) 180 | }).done(function () { 181 | alert('댓글이 등록되었습니다.'); 182 | window.location.reload(); 183 | }).fail(function (error) { 184 | alert(JSON.stringify(error)); 185 | }); 186 | } 187 | }, 188 | /** 댓글 수정 */ 189 | commentUpdate : function (form) { 190 | const data = { 191 | id: form.querySelector('#id').value, 192 | postsId: form.querySelector('#postsId').value, 193 | comment: form.querySelector('#comment-content').value, 194 | writerUserId: form.querySelector('#writerUserId').value, 195 | sessionUserId: form.querySelector('#sessionUserId').value 196 | } 197 | console.log("commentWriterID : " + data.writerUserId); 198 | console.log("sessionUserID : " + data.sessionUserId); 199 | console.log("commentId : " + data.id); 200 | console.log("postId : " + data.postsId); 201 | 202 | if (data.writerUserId !== data.sessionUserId) { 203 | alert("본인이 작성한 댓글만 수정 가능합니다."); 204 | return false; 205 | } 206 | 207 | if (!data.comment || data.comment.trim() === "") { 208 | alert("공백 또는 입력하지 않은 부분이 있습니다."); 209 | return false; 210 | } 211 | const con_check = confirm("수정하시겠습니까?"); 212 | if (con_check === true) { 213 | $.ajax({ 214 | type: 'PUT', 215 | url: '/api/posts/' + data.postsId + '/comments/' + data.id, 216 | dataType: 'JSON', 217 | contentType: 'application/json; charset=utf-8', 218 | data: JSON.stringify(data) 219 | }).done(function () { 220 | window.location.reload(); 221 | }).fail(function (error) { 222 | alert(JSON.stringify(error)); 223 | }); 224 | } 225 | }, 226 | 227 | /** 댓글 삭제 */ 228 | commentDelete : function (postsId, commentId, commentWriterId, sessionUserId) { 229 | 230 | // 본인이 작성한 글인지 확인 231 | if (commentWriterId !== sessionUserId) { 232 | alert("본인이 작성한 댓글만 삭제 가능합니다."); 233 | } else { 234 | const con_check = confirm("삭제하시겠습니까?"); 235 | console.log("postId : " + postsId + "commentId : " + commentId); 236 | if (con_check === true) { 237 | $.ajax({ 238 | type: 'DELETE', 239 | url: '/api/posts/' + postsId + '/comments/' + commentId, 240 | dataType: 'JSON', 241 | }).done(function () { 242 | alert('댓글이 삭제되었습니다.'); 243 | window.location.reload(); 244 | }).fail(function (error) { 245 | alert(JSON.stringify(error)); 246 | }); 247 | } 248 | } 249 | } 250 | }; 251 | 252 | main.init(); -------------------------------------------------------------------------------- /src/main/resources/templates/comment/form.mustache: -------------------------------------------------------------------------------- 1 |
2 |
Write a Comment
3 | {{! 댓글작성 부분}} 4 |
5 | 6 | {{#user}} 7 |
8 | 9 |
10 | 13 | {{/user}} 14 | {{^user}} 15 |
로그인을 하시면 댓글을 등록할 수 있습니다.
16 | {{/user}} 17 |
18 |
-------------------------------------------------------------------------------- /src/main/resources/templates/comment/list.mustache: -------------------------------------------------------------------------------- 1 | {{! Comments }} 2 |
3 |
{{#comments.size}}{{comments.size}}{{/comments.size}} Comments
4 | {{! 댓글내용 부분 }} 5 |
    6 | {{#comments}} 7 |
  • 8 | 9 | {{nickname}} 10 | {{createdDate}} 11 | 12 | {{#isWriter}} 13 | {{! 댓글 수정 버튼 }} 15 | {{! 댓글 삭제 버튼 }} 17 | {{/isWriter}} 18 | 19 | {{! 댓글 내용 보기 }} 20 |

    {{comment}}

    21 | 22 | {{! 댓글 내용 수정 }} 23 |
    24 | 25 | 26 | 27 | 28 |
    29 | 30 |
    31 | 32 |
    33 |
  • 34 | {{/comments}} 35 |
36 |
37 |
-------------------------------------------------------------------------------- /src/main/resources/templates/index.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | {{#posts}} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {{/posts}} 24 | 25 |
번호제목작성자작성일조회수
{{id}}{{title}}{{writer}}{{createdDate}}{{view}}
26 |
27 | 글쓰기 28 |
29 | {{! Page }} 30 | {{>posts/posts-page}} 31 |
32 | {{>layout/footer}} 33 | -------------------------------------------------------------------------------- /src/main/resources/templates/layout/footer.mustache: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | Powered by Lee Ho Jun 7 | 8 | 9 | 010-8515-3275 10 |
11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/templates/layout/header.mustache: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Board Service 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 19 | 20 | 35 | 36 | -------------------------------------------------------------------------------- /src/main/resources/templates/posts/posts-page.mustache: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/resources/templates/posts/posts-read.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 |
6 |
7 | 8 | {{! label 연결 }} 9 | 10 |
11 |
12 | 13 | 14 |
15 |
16 | 17 | 18 |
19 | 20 | 21 |
22 |
23 | 24 | 25 | {{! Buttons }} 26 | {{#user}} 27 | 목록 28 | {{#writer}} 29 | 수정 30 | 31 | {{/writer}} 32 | {{/user}} 33 | {{^user}} 34 | 목록 35 | {{/user}} 36 | {{! Comments }} 37 | {{>comment/list}} 38 | {{>comment/form}} 39 |
40 |
41 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/posts/posts-search.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {{#searchList}} 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | {{/searchList}} 23 | 24 |
번호제목작성자작성일조회수
{{id}}{{title}}{{writer}}{{modifiedDate}}{{view}}
25 |
26 | 글쓰기 27 |
28 | 29 | {{! Search Paging }} 30 | 45 | 46 |
47 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/posts/posts-update.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 |
6 |
7 | 8 | {{! label 연결 }} 9 | 10 |
11 |
12 | 13 | 14 |
15 |
16 | 17 | 18 |
19 | 20 |
21 | 22 | 23 |
24 |
25 | 26 | 27 | 취소 28 | 29 |
30 |
31 | 32 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/posts/posts-write.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 |
6 | 7 | 8 |
9 | 10 |
11 | 12 | 13 |
14 |
15 | 16 | 목록 17 |
18 |
19 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/user/user-join.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 | 6 |
7 | 8 | 9 | {{#valid_username}} {{valid_username}} {{/valid_username}} 10 | 11 |
12 | 13 |
14 | 15 | 16 | {{#valid_password}} {{valid_password}} {{/valid_password}} 17 |
18 | 19 |
20 | 21 | 22 | {{#valid_nickname}} {{valid_nickname}} {{/valid_nickname}} 23 |
24 | 25 |
26 | 27 | 28 | {{#valid_email}} {{valid_email}} {{/valid_email}} 29 |
30 | 31 | 32 | 목록 33 |
34 |
35 |
36 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/user/user-login.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 | 6 |
7 | 8 | 9 |
10 | 11 |
12 | 13 | 14 |
15 | 16 | 17 | {{#error}} 18 |

{{exception}}

19 | {{/error}} 20 |
21 | 22 | 23 |
24 |
25 |
26 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/main/resources/templates/user/user-modify.mustache: -------------------------------------------------------------------------------- 1 | {{>layout/header}} 2 |
3 |
4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 |
12 | 13 |
14 | 15 | 16 |
17 | 18 |
19 | 20 | 21 |
22 | 23 |
24 | 25 | 26 |
27 |
28 | 29 | 목록 30 |
31 |
32 | {{>layout/footer}} -------------------------------------------------------------------------------- /src/test/java/com/coco/board/BoardApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.coco.board; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class BoardApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/coco/board/controller/PostsApiControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.controller; 2 | 3 | import com.coco.board.domain.Posts; 4 | import com.coco.board.infrastructure.persistence.PostsRepository; 5 | import com.coco.board.application.dto.PostsDto; 6 | import org.junit.jupiter.api.AfterEach; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.extension.ExtendWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.web.client.TestRestTemplate; 12 | import org.springframework.boot.web.server.LocalServerPort; 13 | import org.springframework.http.HttpEntity; 14 | import org.springframework.http.HttpMethod; 15 | import org.springframework.http.HttpStatus; 16 | import org.springframework.http.ResponseEntity; 17 | import org.springframework.test.context.junit.jupiter.SpringExtension; 18 | 19 | import java.util.List; 20 | 21 | import static org.assertj.core.api.Assertions.*; 22 | 23 | @ExtendWith(SpringExtension.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | public class PostsApiControllerTest { 26 | 27 | @Autowired 28 | private PostsRepository postsRepository; 29 | 30 | @LocalServerPort 31 | private int port; 32 | 33 | @Autowired 34 | private TestRestTemplate restTemplate; 35 | 36 | @AfterEach 37 | public void clear() { 38 | postsRepository.deleteAll(); 39 | } 40 | 41 | @Test 42 | public void 게시글_수정_테스트() { 43 | 44 | Posts savePosts = postsRepository.save(Posts.builder() 45 | .title("title") 46 | .writer("writer") 47 | .content("content") 48 | .build()); 49 | 50 | Long updateId = savePosts.getId(); 51 | String changeTitle = "title2"; 52 | String changeContent = "content2"; 53 | 54 | PostsDto.Request requestDto = PostsDto.Request.builder() 55 | .title(changeTitle) 56 | .content(changeContent) 57 | .build(); 58 | 59 | String url = "http://localhost:" + port + "/api/posts/" + updateId; 60 | 61 | HttpEntity requestEntity = new HttpEntity<>(requestDto); 62 | 63 | ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Long.class); 64 | 65 | assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); 66 | assertThat(responseEntity.getBody()).isGreaterThan(0L); 67 | 68 | List all = postsRepository.findAll(); 69 | 70 | assertThat(all.get(0).getTitle()).isEqualTo(changeTitle); 71 | assertThat(all.get(0).getContent()).isEqualTo(changeContent); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/test/java/com/coco/board/domain/CommentRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import com.coco.board.infrastructure.persistence.CommentRepository; 4 | import org.junit.jupiter.api.AfterEach; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | import java.util.List; 10 | import java.util.stream.IntStream; 11 | 12 | import static org.assertj.core.api.Assertions.*; 13 | 14 | @SpringBootTest 15 | public class CommentRepositoryTest { 16 | 17 | @Autowired 18 | CommentRepository commentRepository; 19 | 20 | @AfterEach 21 | public void clear() { 22 | commentRepository.deleteAll(); 23 | } 24 | 25 | @Test 26 | public void 게시글_댓글_생성_조회() { 27 | String content = "댓글 입니다."; 28 | 29 | Posts posts = Posts.builder().id(1L).build(); 30 | User user = User.builder().id(1L).build(); 31 | 32 | commentRepository.save(Comment.builder() 33 | .comment(content) 34 | .user(user) 35 | .posts(posts) 36 | .build()); 37 | 38 | List comments = commentRepository.getCommentByPostsOrderById(posts); 39 | 40 | Comment comment = comments.get(0); 41 | 42 | assertThat(comment.getComment()).isEqualTo(content); 43 | } 44 | 45 | @Test 46 | public void 랜덤_댓글_생성() { 47 | IntStream.rangeClosed(1, 20).forEach(i -> { 48 | long id = (long)(Math.random() * 22) + 1; 49 | 50 | Posts posts = Posts.builder().id(id).build(); 51 | User user = User.builder().id(id).build(); 52 | Comment comment = Comment.builder() 53 | .comment(i + "번째 댓글입니다.") 54 | .user(user) 55 | .posts(posts) 56 | .build(); 57 | 58 | commentRepository.save(comment); 59 | }); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/coco/board/domain/PostsRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import com.coco.board.infrastructure.persistence.PostsRepository; 4 | import lombok.extern.log4j.Log4j2; 5 | import org.junit.jupiter.api.AfterEach; 6 | import org.junit.jupiter.api.BeforeEach; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import java.util.List; 12 | 13 | import static org.assertj.core.api.Assertions.*; 14 | 15 | 16 | @SpringBootTest 17 | @Log4j2 18 | public class PostsRepositoryTest { 19 | 20 | @Autowired 21 | private PostsRepository postsRepository; 22 | 23 | @BeforeEach 24 | public void reset() { 25 | postsRepository.deleteAll(); 26 | } 27 | 28 | @AfterEach 29 | public void clear() { 30 | postsRepository.deleteAll(); 31 | } 32 | 33 | @Test 34 | public void 게시글_생성_가져오기() { 35 | String title = "제목 입니다."; 36 | String content = "내용 입니다"; 37 | 38 | postsRepository.save(Posts.builder().title(title).content(content).writer("coco").build()); 39 | 40 | List postsList = postsRepository.findAll(); 41 | 42 | Posts posts = postsList.get(0); 43 | 44 | assertThat(posts.getTitle()).isEqualTo(title); 45 | assertThat(posts.getContent()).isEqualTo(content); 46 | 47 | log.info(posts); 48 | } 49 | } -------------------------------------------------------------------------------- /src/test/java/com/coco/board/domain/UserRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.domain; 2 | 3 | import com.coco.board.infrastructure.persistence.UserRepository; 4 | import org.junit.jupiter.api.AfterEach; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 9 | 10 | import java.util.List; 11 | 12 | import static org.assertj.core.api.Assertions.*; 13 | 14 | @SpringBootTest 15 | public class UserRepositoryTest { 16 | 17 | @Autowired 18 | private UserRepository userRepository; 19 | 20 | @Autowired 21 | private BCryptPasswordEncoder encoder; 22 | 23 | @AfterEach 24 | public void clear() { 25 | userRepository.deleteAll(); 26 | } 27 | 28 | @Test 29 | public void 유저_생성_가져오기() { 30 | String username = "coco"; 31 | String rawPassword = "123!@#qwe"; 32 | String encPassword = encoder.encode(rawPassword); 33 | userRepository.save(User.builder().username(username).password(encPassword).nickname("홍길동").email("coco@nate.com").role(Role.USER).build()); 34 | 35 | List userList = userRepository.findAll(); 36 | 37 | User user = userList.get(0); 38 | 39 | assertThat(user.getUsername()).isEqualTo(username); 40 | assertThat(user.getPassword()).isEqualTo(encPassword); 41 | } 42 | } -------------------------------------------------------------------------------- /src/test/java/com/coco/board/infrastructure/config/SecurityConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.infrastructure.config; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 5 | 6 | 7 | public class SecurityConfigTest { 8 | 9 | @Test 10 | public void 해쉬_암호화() { 11 | String encodePassword = new BCryptPasswordEncoder().encode("1234"); 12 | System.out.println("1234 해쉬 : " + encodePassword); 13 | } 14 | } -------------------------------------------------------------------------------- /src/test/java/com/coco/board/service/PostsServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.coco.board.service; 2 | 3 | import com.coco.board.application.PostsService; 4 | import com.coco.board.infrastructure.persistence.PostsRepository; 5 | import com.coco.board.domain.Role; 6 | import com.coco.board.domain.User; 7 | import com.coco.board.infrastructure.persistence.UserRepository; 8 | import com.coco.board.application.dto.PostsDto; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.junit.jupiter.api.AfterEach; 11 | import org.junit.jupiter.api.Test; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.test.context.SpringBootTest; 14 | 15 | @SpringBootTest 16 | @Slf4j 17 | public class PostsServiceTest { 18 | 19 | @Autowired 20 | PostsService postsService; 21 | 22 | @Autowired 23 | PostsRepository postsRepository; 24 | 25 | @Autowired 26 | UserRepository userRepository; 27 | 28 | @AfterEach 29 | public void clear() { 30 | postsRepository.deleteAll(); 31 | } 32 | 33 | @Test 34 | public void 게시글_생성() { 35 | User user = User.builder().username("coco").nickname("coco").email("coco@coco.co").role(Role.USER).build(); 36 | 37 | PostsDto.Request posts = PostsDto.Request.builder() 38 | .title("Test Title") 39 | .writer(user.getNickname()) 40 | .content("Test Content") 41 | .view(0) 42 | .user(user) 43 | .build(); 44 | 45 | postsService.save(posts, user.getNickname()); 46 | 47 | log.info(String.valueOf(posts)); 48 | } 49 | } --------------------------------------------------------------------------------