├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── cos │ │ └── blog │ │ ├── BlogApplication.java │ │ ├── config │ │ ├── SecurityConfig.java │ │ └── auth │ │ │ ├── PrincipalDetail.java │ │ │ └── PrincipalDetailService.java │ │ ├── controller │ │ ├── BoardController.java │ │ ├── UserController.java │ │ └── api │ │ │ ├── BoardApiController.java │ │ │ └── UserApiController.java │ │ ├── dto │ │ ├── ReplySaveRequestDto.java │ │ └── ResponseDto.java │ │ ├── handler │ │ └── GlobalExceptionHandler.java │ │ ├── model │ │ ├── Board.java │ │ ├── KakaoProfile.java │ │ ├── OAuthToken.java │ │ ├── Reply.java │ │ ├── RoleType.java │ │ └── User.java │ │ ├── repository │ │ ├── BoardRepository.java │ │ ├── ReplyRepository.java │ │ └── UserRepository.java │ │ ├── service │ │ ├── BoardService.java │ │ └── UserService.java │ │ └── test │ │ ├── BlogControllerTest.java │ │ ├── DummyControllerTest.java │ │ ├── HttpControllerTest.java │ │ ├── Member.java │ │ ├── ReplyControllerTest.java │ │ └── TempControllerTest.java ├── resources │ ├── application-dev.yml │ ├── application-test.yml │ ├── application.yml │ └── static │ │ ├── image │ │ └── kakao_login_button.png │ │ └── js │ │ ├── board.js │ │ └── user.js └── webapp │ └── WEB-INF │ └── views │ ├── board │ ├── detail.jsp │ ├── saveForm.jsp │ └── updateForm.jsp │ ├── index.jsp │ ├── layout │ ├── footer.jsp │ └── header.jsp │ └── user │ ├── joinForm.jsp │ ├── loginForm.jsp │ └── updateForm.jsp └── test └── java └── com └── cos └── blog ├── EncTest.java └── ReplyObjectTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingspecialist/Springboot-JPA-Blog/05e9ba257d908f7b09f518a46b251e4d390f63e3/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 스프링 3.x 버전으로 따라하시는 분들 2 | ```text 3 | 스프링 3.x 버전은 최소 JDK 버전이 17입니다. 4 | ``` 5 | 6 | ### maven 의존성과 시큐리티 변경된 코드 7 | 브랜치 update-202403 을 참고하세요 8 | 9 | ### mysql 연결 10 | ```sql 11 | create user 'cos'@'%' identified by 'cos1234'; 12 | GRANT ALL PRIVILEGES ON *.* TO 'cos'@'%'; 13 | create database blog; 14 | ``` 15 | 16 | ### gradle 의존성 17 | ```gradle 18 | dependencies { 19 | implementation 'org.apache.tomcat:tomcat-jasper:11.0.0-M16' 20 | implementation 'jakarta.servlet:jakarta.servlet-api' 21 | implementation 'jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api' 22 | implementation 'org.glassfish.web:jakarta.servlet.jsp.jstl' 23 | 24 | //implementation 'org.springframework.boot:spring-boot-starter-security' 25 | //implementation 'org.springframework.security:spring-security-taglibs' 26 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 27 | implementation 'org.springframework.boot:spring-boot-starter-web' 28 | compileOnly 'org.projectlombok:lombok' 29 | annotationProcessor 'org.projectlombok:lombok' 30 | developmentOnly 'org.springframework.boot:spring-boot-devtools' 31 | 32 | runtimeOnly 'com.mysql:mysql-connector-j' 33 | 34 | // 테스트 DB 임시 35 | runtimeOnly 'com.h2database:h2' 36 | 37 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 38 | testImplementation 'org.springframework.security:spring-security-test' 39 | } 40 | ``` -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.14 9 | 10 | 11 | com.cos 12 | blog 13 | 0.0.1-SNAPSHOT 14 | blog 15 | My First Blog Project 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | com.h2database 27 | h2 28 | runtime 29 | 30 | 31 | 32 | org.springframework.security 33 | spring-security-taglibs 34 | 35 | 36 | 37 | 38 | 39 | org.apache.tomcat.embed 40 | tomcat-embed-jasper 41 | 42 | 43 | 44 | 45 | 46 | javax.servlet 47 | jstl 48 | 1.2 49 | 50 | 51 | 52 | 53 | 54 | 55 | mysql 56 | mysql-connector-java 57 | 8.0.22 58 | 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-starter-data-jpa 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-security 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-starter-web 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-devtools 78 | runtime 79 | true 80 | 81 | 82 | 83 | 84 | 85 | org.projectlombok 86 | lombok 87 | true 88 | 89 | 90 | org.springframework.boot 91 | spring-boot-starter-test 92 | test 93 | 94 | 95 | org.junit.vintage 96 | junit-vintage-engine 97 | 98 | 99 | 100 | 101 | org.springframework.security 102 | spring-security-test 103 | test 104 | 105 | 106 | 107 | 108 | 109 | 110 | org.springframework.boot 111 | spring-boot-maven-plugin 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/BlogApplication.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BlogApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BlogApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 9 | import org.springframework.security.web.SecurityFilterChain; 10 | 11 | // 1. 어노테이션 제거 12 | @Configuration 13 | public class SecurityConfig{ // 2. extends 제거 14 | 15 | // 3. principalDetailService 제거 16 | 17 | // 4. AuthenticationManager 메서드 생성 18 | @Bean 19 | public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { 20 | return authenticationConfiguration.getAuthenticationManager(); 21 | } 22 | 23 | @Bean // IoC가 되요!! 24 | public BCryptPasswordEncoder encodePWD() { 25 | return new BCryptPasswordEncoder(); 26 | } 27 | 28 | // 5. 기본 패스워드 체크가 BCryptPasswordEncoder 여서 설정 필요 없음. 29 | 30 | 31 | // 6. 최신 버전(2.7)으로 시큐리티 필터 변경 32 | @Bean 33 | SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 34 | // 1. csrf 비활성화 35 | http.csrf().disable(); 36 | 37 | // 2. 인증 주소 설정 38 | http.authorizeRequests( 39 | authorize -> authorize.antMatchers("/", "/auth/**", "/js/**", "/css/**", "/image/**", "/dummy/**").permitAll() 40 | .anyRequest().authenticated() 41 | ); 42 | 43 | // 3. 로그인 처리 프로세스 설정 44 | http.formLogin(f -> f.loginPage("/auth/loginForm") 45 | .loginProcessingUrl("/auth/loginProc") 46 | .defaultSuccessUrl("/") 47 | ); 48 | 49 | return http.build(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/config/auth/PrincipalDetail.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.config.auth; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | 9 | import com.cos.blog.model.User; 10 | 11 | import lombok.Data; 12 | import lombok.Getter; 13 | 14 | // 스프링 시큐리티가 로그인 요청을 가로채서 로그인을 진행하고 완료가 되면 UserDetails 타입의 오브젝트를 15 | // 스프링 시큐리티의 고유한 세션저장소에 저장을 해준다. 16 | @Data 17 | public class PrincipalDetail implements UserDetails{ 18 | private User user; // 콤포지션 19 | 20 | public PrincipalDetail(User user) { 21 | this.user = user; 22 | } 23 | 24 | @Override 25 | public String getPassword() { 26 | return user.getPassword(); 27 | } 28 | 29 | @Override 30 | public String getUsername() { 31 | return user.getUsername(); 32 | } 33 | 34 | // 계정이 만료되지 않았는지 리턴한다. (true: 만료안됨) 35 | @Override 36 | public boolean isAccountNonExpired() { 37 | return true; 38 | } 39 | 40 | // 계정이 잠겨있지 않았는지 리턴한다. (true: 잠기지 않음) 41 | @Override 42 | public boolean isAccountNonLocked() { 43 | return true; 44 | } 45 | 46 | // 비밀번호가 만료되지 않았는지 리턴한다. (true: 만료안됨) 47 | @Override 48 | public boolean isCredentialsNonExpired() { 49 | return true; 50 | } 51 | 52 | // 계정이 활성화(사용가능)인지 리턴한다. (true: 활성화) 53 | @Override 54 | public boolean isEnabled() { 55 | return true; 56 | } 57 | 58 | // 계정이 갖고있는 권한 목록을 리턴한다. (권한이 여러개 있을 수 있어서 루프를 돌아야 하는데 우리는 한개만) 59 | @Override 60 | public Collection extends GrantedAuthority> getAuthorities() { 61 | 62 | Collection collectors = new ArrayList<>(); 63 | collectors.add(()->{ return "ROLE_"+user.getRole();}); 64 | 65 | return collectors; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/config/auth/PrincipalDetailService.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.config.auth; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.cos.blog.model.User; 10 | import com.cos.blog.repository.UserRepository; 11 | 12 | @Service // Bean 등록 13 | public class PrincipalDetailService implements UserDetailsService{ 14 | 15 | @Autowired 16 | private UserRepository userRepository; 17 | 18 | // 스프링이 로그인 요청을 가로챌 때, username, password 변수 2개를 가로채는데 19 | // password 부분 처리는 알아서 함. 20 | // username이 DB에 있는지만 확인해주면 됨. 21 | @Override 22 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 23 | User principal = userRepository.findByUsername(username) 24 | .orElseThrow(()->{ 25 | return new UsernameNotFoundException("해당 사용자를 찾을 수 없습니다. : "+username); 26 | }); 27 | return new PrincipalDetail(principal); // 시큐리티의 세션에 유저 정보가 저장이 됨. 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/controller/BoardController.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.domain.Sort; 6 | import org.springframework.data.web.PageableDefault; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.ui.Model; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | 12 | import com.cos.blog.service.BoardService; 13 | 14 | @Controller 15 | public class BoardController { 16 | 17 | @Autowired 18 | private BoardService boardService; 19 | 20 | // 컨트롤로에서 세션을 어떻게 찾는지? 21 | // @AuthenticationPrincipal PrincipalDetail principal 22 | @GetMapping({"", "/"}) 23 | public String index(Model model, @PageableDefault(size=3, sort="id", direction = Sort.Direction.DESC) Pageable pageable) { 24 | model.addAttribute("boards", boardService.글목록(pageable)); 25 | return "index"; // viewResolver 작동!! 26 | } 27 | 28 | @GetMapping("/board/{id}") 29 | public String findById(@PathVariable int id, Model model) { 30 | model.addAttribute("board", boardService.글상세보기(id)); 31 | 32 | return "board/detail"; 33 | } 34 | 35 | @GetMapping("/board/{id}/updateForm") 36 | public String updateForm(@PathVariable int id, Model model) { 37 | model.addAttribute("board", boardService.글상세보기(id)); 38 | return "board/updateForm"; 39 | } 40 | 41 | // USER 권한이 필요 42 | @GetMapping("/board/saveForm") 43 | public String saveForm() { 44 | return "board/saveForm"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.controller; 2 | 3 | import com.cos.blog.config.auth.PrincipalDetail; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.http.HttpEntity; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpMethod; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.context.SecurityContext; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.web.context.HttpSessionSecurityContextRepository; 16 | import org.springframework.stereotype.Controller; 17 | import org.springframework.util.LinkedMultiValueMap; 18 | import org.springframework.util.MultiValueMap; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import com.cos.blog.model.KakaoProfile; 23 | import com.cos.blog.model.OAuthToken; 24 | import com.cos.blog.model.User; 25 | import com.cos.blog.service.UserService; 26 | import com.fasterxml.jackson.core.JsonProcessingException; 27 | import com.fasterxml.jackson.databind.JsonMappingException; 28 | import com.fasterxml.jackson.databind.ObjectMapper; 29 | 30 | import javax.servlet.http.HttpSession; 31 | 32 | // 인증이 안된 사용자들이 출입할 수 있는 경로를 /auth/** 허용 33 | // 그냥 주소가 / 이면 index.jsp 허용 34 | // static이하에 있는 /js/**, /css/**, /image/** 35 | 36 | @Controller 37 | public class UserController { 38 | 39 | @Value("${cos.key}") 40 | private String cosKey; 41 | 42 | @Autowired 43 | private AuthenticationManager authenticationManager; 44 | 45 | @Autowired 46 | private UserService userService; 47 | 48 | @Autowired 49 | private HttpSession session; 50 | 51 | @GetMapping("/auth/joinForm") 52 | public String joinForm() { 53 | return "user/joinForm"; 54 | } 55 | 56 | @GetMapping("/auth/loginForm") 57 | public String loginForm() { 58 | return "user/loginForm"; 59 | } 60 | 61 | @GetMapping("/auth/kakao/callback") 62 | public String kakaoCallback(String code) { // Data를 리턴해주는 컨트롤러 함수 63 | 64 | // POST방식으로 key=value 데이터를 요청 (카카오쪽으로) 65 | // Retrofit2 66 | // OkHttp 67 | // RestTemplate 68 | 69 | RestTemplate rt = new RestTemplate(); 70 | 71 | // HttpHeader 오브젝트 생성 72 | HttpHeaders headers = new HttpHeaders(); 73 | headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); 74 | 75 | // HttpBody 오브젝트 생성 76 | MultiValueMap params = new LinkedMultiValueMap<>(); 77 | params.add("grant_type", "authorization_code"); 78 | params.add("client_id", "b344701c3ff69917f13cd47bb45df871"); 79 | params.add("redirect_uri", "http://localhost:8000/auth/kakao/callback"); 80 | params.add("code", code); 81 | 82 | // HttpHeader와 HttpBody를 하나의 오브젝트에 담기 83 | HttpEntity> kakaoTokenRequest = 84 | new HttpEntity<>(params, headers); 85 | 86 | // Http 요청하기 - Post방식으로 - 그리고 response 변수의 응답 받음. 87 | ResponseEntity response = rt.exchange( 88 | "https://kauth.kakao.com/oauth/token", 89 | HttpMethod.POST, 90 | kakaoTokenRequest, 91 | String.class 92 | ); 93 | 94 | // Gson, Json Simple, ObjectMapper 95 | ObjectMapper objectMapper = new ObjectMapper(); 96 | OAuthToken oauthToken = null; 97 | try { 98 | oauthToken = objectMapper.readValue(response.getBody(), OAuthToken.class); 99 | } catch (JsonMappingException e) { 100 | e.printStackTrace(); 101 | } catch (JsonProcessingException e) { 102 | e.printStackTrace(); 103 | } 104 | 105 | System.out.println("카카오 엑세스 토큰 : "+oauthToken.getAccess_token()); 106 | 107 | RestTemplate rt2 = new RestTemplate(); 108 | 109 | // HttpHeader 오브젝트 생성 110 | HttpHeaders headers2 = new HttpHeaders(); 111 | headers2.add("Authorization", "Bearer "+oauthToken.getAccess_token()); 112 | headers2.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); 113 | 114 | // HttpHeader와 HttpBody를 하나의 오브젝트에 담기 115 | HttpEntity> kakaoProfileRequest2 = 116 | new HttpEntity<>(headers2); 117 | 118 | // Http 요청하기 - Post방식으로 - 그리고 response 변수의 응답 받음. 119 | ResponseEntity response2 = rt2.exchange( 120 | "https://kapi.kakao.com/v2/user/me", 121 | HttpMethod.POST, 122 | kakaoProfileRequest2, 123 | String.class 124 | ); 125 | System.out.println(response2.getBody()); 126 | 127 | ObjectMapper objectMapper2 = new ObjectMapper(); 128 | KakaoProfile kakaoProfile = null; 129 | try { 130 | kakaoProfile = objectMapper2.readValue(response2.getBody(), KakaoProfile.class); 131 | } catch (JsonMappingException e) { 132 | e.printStackTrace(); 133 | } catch (JsonProcessingException e) { 134 | e.printStackTrace(); 135 | } 136 | 137 | // User 오브젝트 : username, password, email 138 | System.out.println("카카오 아이디(번호) : "+kakaoProfile.getId()); 139 | System.out.println("카카오 이메일 : "+kakaoProfile.getKakao_account().getEmail()); 140 | 141 | System.out.println("블로그서버 유저네임 : "+kakaoProfile.getKakao_account().getEmail()+"_"+kakaoProfile.getId()); 142 | System.out.println("블로그서버 이메일 : "+kakaoProfile.getKakao_account().getEmail()); 143 | // UUID란 -> 중복되지 않는 어떤 특정 값을 만들어내는 알고리즘 144 | System.out.println("블로그서버 패스워드 : "+cosKey); 145 | 146 | User kakaoUser = User.builder() 147 | .username(kakaoProfile.getKakao_account().getEmail()+"_"+kakaoProfile.getId()) 148 | .password(cosKey) 149 | .email(kakaoProfile.getKakao_account().getEmail()) 150 | .oauth("kakao") 151 | .build(); 152 | 153 | // 가입자 혹은 비가입자 체크 해서 처리 154 | User originUser = userService.회원찾기(kakaoUser.getUsername()); 155 | 156 | if(originUser.getUsername() == null) { 157 | System.out.println("기존 회원이 아니기에 자동 회원가입을 진행합니다"); 158 | userService.회원가입(kakaoUser); 159 | } 160 | 161 | System.out.println("자동 로그인을 진행합니다."); 162 | // 로그인 처리 163 | // (1. UsernamePasswordAuthenticationToken 토큰 생성시 이제 정확한 정보를 추가해줘야 한다 UserDetails, password, role) 164 | // (2. SecurityContext에 Authentication 객체를 추가하면 예전에는 세션이 만들어졌다) 165 | // (3. 이제는 보안때문에, 해당 컨텍스트를 세션에 직접 주입해줘야 한다 HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY) 166 | PrincipalDetail principalDetail = new PrincipalDetail(kakaoUser); 167 | Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(principalDetail, principalDetail.getPassword(), principalDetail.getAuthorities())); 168 | SecurityContext securityContext = SecurityContextHolder.getContext(); 169 | securityContext.setAuthentication(authentication); 170 | session.setAttribute(HttpSessionSecurityContextRepository. 171 | SPRING_SECURITY_CONTEXT_KEY, securityContext); 172 | return "redirect:/"; 173 | } 174 | 175 | @GetMapping("/user/updateForm") 176 | public String updateForm() { 177 | return "user/updateForm"; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/controller/api/BoardApiController.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.controller.api; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 6 | import org.springframework.web.bind.annotation.DeleteMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.PutMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import com.cos.blog.config.auth.PrincipalDetail; 14 | import com.cos.blog.dto.ReplySaveRequestDto; 15 | import com.cos.blog.dto.ResponseDto; 16 | import com.cos.blog.model.Board; 17 | import com.cos.blog.service.BoardService; 18 | 19 | @RestController 20 | public class BoardApiController { 21 | 22 | @Autowired 23 | private BoardService boardService; 24 | 25 | @PostMapping("/api/board") 26 | public ResponseDto save(@RequestBody Board board, @AuthenticationPrincipal PrincipalDetail principal) { 27 | boardService.글쓰기(board, principal.getUser()); 28 | return new ResponseDto(HttpStatus.OK.value(), 1); 29 | } 30 | 31 | @DeleteMapping("/api/board/{id}") 32 | public ResponseDto deleteById(@PathVariable int id){ 33 | boardService.글삭제하기(id); 34 | return new ResponseDto(HttpStatus.OK.value(), 1); 35 | } 36 | 37 | @PutMapping("/api/board/{id}") 38 | public ResponseDto update(@PathVariable int id, @RequestBody Board board){ 39 | System.out.println("BoardApiController : update : id : "+id); 40 | System.out.println("BoardApiController : update : board : "+board.getTitle()); 41 | System.out.println("BoardApiController : update : board : "+board.getContent()); 42 | boardService.글수정하기(id, board); 43 | return new ResponseDto(HttpStatus.OK.value(), 1); 44 | } 45 | 46 | // 데이터 받을 때 컨트롤러에서 dto를 만들어서 받는게 좋다. 47 | // dto 사용하지 않은 이유는!! 48 | @PostMapping("/api/board/{boardId}/reply") 49 | public ResponseDto replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) { 50 | boardService.댓글쓰기(replySaveRequestDto); 51 | return new ResponseDto(HttpStatus.OK.value(), 1); 52 | } 53 | 54 | @DeleteMapping("/api/board/{boardId}/reply/{replyId}") 55 | public ResponseDto replyDelete(@PathVariable int replyId) { 56 | boardService.댓글삭제(replyId); 57 | return new ResponseDto(HttpStatus.OK.value(), 1); 58 | } 59 | } 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/controller/api/UserApiController.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.controller.api; 2 | 3 | import com.cos.blog.config.auth.PrincipalDetail; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.PutMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import com.cos.blog.dto.ResponseDto; 18 | import com.cos.blog.model.User; 19 | import com.cos.blog.service.UserService; 20 | 21 | @RestController 22 | public class UserApiController { 23 | 24 | @Autowired 25 | private UserService userService; 26 | 27 | @Autowired 28 | private AuthenticationManager authenticationManager; 29 | 30 | @PostMapping("/auth/joinProc") 31 | public ResponseDto save(@RequestBody User user) { // username, password, email 32 | System.out.println("UserApiController : save 호출됨"); 33 | userService.회원가입(user); 34 | return new ResponseDto(HttpStatus.OK.value(), 1); // 자바오브젝트를 JSON으로 변환해서 리턴 (Jackson) 35 | } 36 | 37 | @PutMapping("/user") 38 | public ResponseDto update(@RequestBody User user, @AuthenticationPrincipal PrincipalDetail principalDetail) { // key=value, x-www-form-urlencoded 39 | userService.회원수정(user); 40 | // 여기서는 트랜잭션이 종료되기 때문에 DB에 값은 변경이 됐음. 41 | // 하지만 세션값은 변경되지 않은 상태이기 때문에 우리가 직접 세션값을 변경해줄 것임. 42 | // 세션 등록 43 | 44 | // 세션 변경은 principalDetail 값만 변경하면 된다. 45 | principalDetail.setUser(user); 46 | 47 | // deprecate (이제 아래 코드 안씀) 48 | // Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())); 49 | // SecurityContextHolder.getContext().setAuthentication(authentication); 50 | 51 | return new ResponseDto(HttpStatus.OK.value(), 1); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/dto/ReplySaveRequestDto.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @AllArgsConstructor 9 | @NoArgsConstructor 10 | public class ReplySaveRequestDto { 11 | private int userId; 12 | private int boardId; 13 | private String content; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/dto/ResponseDto.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.dto; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @Builder 14 | public class ResponseDto { 15 | int status; 16 | T data; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/handler/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.handler; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ControllerAdvice; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import com.cos.blog.dto.ResponseDto; 9 | 10 | @ControllerAdvice 11 | @RestController 12 | public class GlobalExceptionHandler { 13 | 14 | @ExceptionHandler(value=Exception.class) 15 | public ResponseDto handleArgumentException(Exception e) { 16 | return new ResponseDto(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); // 500 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/Board.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.List; 5 | 6 | import javax.persistence.CascadeType; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | import javax.persistence.JoinColumn; 14 | import javax.persistence.Lob; 15 | import javax.persistence.ManyToOne; 16 | import javax.persistence.OneToMany; 17 | import javax.persistence.OrderBy; 18 | 19 | import org.hibernate.annotations.CreationTimestamp; 20 | 21 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 22 | 23 | import lombok.AllArgsConstructor; 24 | import lombok.Builder; 25 | import lombok.Data; 26 | import lombok.NoArgsConstructor; 27 | 28 | @Data 29 | @NoArgsConstructor 30 | @AllArgsConstructor 31 | @Builder 32 | @Entity 33 | public class Board { 34 | 35 | @Id 36 | @GeneratedValue(strategy = GenerationType.IDENTITY) // auto_increment 37 | private int id; 38 | 39 | @Column(nullable = false, length = 100) 40 | private String title; 41 | 42 | @Lob // 대용량 데이터 43 | private String content; // 섬머노트 라이브러리 태그가 섞여서 디자인이 됨. 44 | 45 | private int count; // 조회수 46 | 47 | @ManyToOne(fetch = FetchType.EAGER) // Many = Many, User = One 48 | @JoinColumn(name="userId") 49 | private User user; // DB는 오브젝트를 저장할 수 없다. FK, 자바는 오브젝트를 저장할 수 있다. 50 | 51 | @OneToMany(mappedBy = "board", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE) // mappedBy 연관관계의 주인이 아니다 (난 FK가 아니에요) DB에 칼럼을 만들지 마세요. 52 | @JsonIgnoreProperties({"board"}) 53 | @OrderBy("id desc") 54 | private List replys; 55 | 56 | @CreationTimestamp 57 | private LocalDateTime createDate; 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/KakaoProfile.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class KakaoProfile { 7 | public Integer id; 8 | public String connected_at; 9 | public Properties properties; 10 | public KakaoAccount kakao_account; 11 | 12 | @Data 13 | public class Properties { 14 | public String nickname; 15 | public String profile_image; 16 | public String thumbnail_image; 17 | } 18 | 19 | @Data 20 | public class KakaoAccount { 21 | public Boolean profile_needs_agreement; 22 | public Profile profile; 23 | public Boolean has_email; 24 | public Boolean email_needs_agreement; 25 | public Boolean is_email_valid; 26 | public Boolean is_email_verified; 27 | public String email; 28 | 29 | @Data 30 | public class Profile { 31 | public String nickname; 32 | public String thumbnail_image_url; 33 | public String profile_image_url; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/OAuthToken.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OAuthToken { 7 | private String access_token; 8 | private String token_type; 9 | private String refresh_token; 10 | private int expires_in; 11 | private String scope; 12 | private int refresh_token_expires_in; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/Reply.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | 13 | import org.hibernate.annotations.CreationTimestamp; 14 | 15 | import com.cos.blog.dto.ReplySaveRequestDto; 16 | import com.cos.blog.repository.ReplyRepository; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Builder; 20 | import lombok.Data; 21 | import lombok.NoArgsConstructor; 22 | 23 | @Builder 24 | @AllArgsConstructor 25 | @NoArgsConstructor 26 | @Data 27 | @Entity 28 | public class Reply { 29 | @Id //Primary key 30 | @GeneratedValue(strategy = GenerationType.IDENTITY) // 프로젝트에서 연결된 DB의 넘버링 전략을 따라간다. 31 | private int id; // 시퀀스, auto_increment 32 | 33 | @Column(nullable = false, length = 200) 34 | private String content; 35 | 36 | @ManyToOne 37 | @JoinColumn(name="boardId") 38 | private Board board; 39 | 40 | @ManyToOne 41 | @JoinColumn(name="userId") 42 | private User user; 43 | 44 | @CreationTimestamp 45 | private LocalDateTime createDate; 46 | 47 | @Override 48 | public String toString() { 49 | return "Reply [id=" + id + ", content=" + content + ", board=" + board + ", user=" + user + ", createDate=" 50 | + createDate + "]"; 51 | } 52 | } 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/RoleType.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | public enum RoleType { 4 | USER, ADMIN 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/model/User.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.model; 2 | 3 | import java.sql.Timestamp; 4 | import java.time.LocalDateTime; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.EnumType; 9 | import javax.persistence.Enumerated; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | 14 | import org.hibernate.annotations.ColumnDefault; 15 | import org.hibernate.annotations.CreationTimestamp; 16 | 17 | import lombok.AllArgsConstructor; 18 | import lombok.Builder; 19 | import lombok.Data; 20 | import lombok.NoArgsConstructor; 21 | 22 | @Data 23 | @NoArgsConstructor 24 | @AllArgsConstructor 25 | @Builder // 빌더 패턴!! 26 | //ORM -> Java(다른언어) Object -> 테이블로 매핑해주는 기술 27 | @Entity // User 클래스가 MySQL에 테이블이 생성이 된다. 28 | // @DynamicInsert // insert시에 null인 필드를 제외시켜준다. 29 | public class User { 30 | 31 | @Id //Primary key 32 | @GeneratedValue(strategy = GenerationType.IDENTITY) // 프로젝트에서 연결된 DB의 넘버링 전략을 따라간다. 33 | private int id; // 시퀀스, auto_increment 34 | 35 | @Column(nullable = false, length = 100, unique = true) 36 | private String username; // 아이디 37 | 38 | @Column(nullable = false, length = 100) // 123456 => 해쉬 (비밀번호 암호화) 39 | private String password; 40 | 41 | @Column(nullable = false, length = 50) 42 | private String email; // myEmail, my_email 43 | 44 | // @ColumnDefault("user") 45 | // DB는 RoleType이라는 게 없다. 46 | @Enumerated(EnumType.STRING) 47 | private RoleType role; // Enum을 쓰는게 좋다. // ADMIN, USER 48 | 49 | private String oauth; // kakao, google 50 | 51 | // 내가 직접 시간을 넣으려면 Timestamp.valueOf(LocalDateTime.now()) 52 | @CreationTimestamp 53 | private Timestamp createDate; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/repository/BoardRepository.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.cos.blog.model.Board; 6 | 7 | public interface BoardRepository extends JpaRepository{ 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/repository/ReplyRepository.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.Modifying; 5 | import org.springframework.data.jpa.repository.Query; 6 | 7 | import com.cos.blog.model.Reply; 8 | 9 | public interface ReplyRepository extends JpaRepository{ 10 | 11 | @Modifying 12 | @Query(value="INSERT INTO reply(userId, boardId, content, createDate) VALUES(?1, ?2, ?3, now())", nativeQuery = true) 13 | int mSave(int userId, int boardId, String content); // 업데이트된 행의 개수를 리턴해줌. 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.repository; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import com.cos.blog.model.User; 10 | 11 | // DAO 12 | // 자동으로 bean등록이 된다. 13 | // @Repository // 생략 가능하다. 14 | public interface UserRepository extends JpaRepository{ 15 | // SELECT * FROM user WHERE username = 1?; 16 | Optional findByUsername(String username); 17 | } 18 | 19 | 20 | // JPA Naming 쿼리 21 | // SELECT * FROM user WHERE username = ?1 AND password = ?2; 22 | //User findByUsernameAndPassword(String username, String password); 23 | 24 | // @Query(value="SELECT * FROM user WHERE username = ?1 AND password = ?2", nativeQuery = true) 25 | // User login(String username, String password); 26 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/service/BoardService.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.service; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import com.cos.blog.dto.ReplySaveRequestDto; 9 | import com.cos.blog.model.Board; 10 | import com.cos.blog.model.User; 11 | import com.cos.blog.repository.BoardRepository; 12 | import com.cos.blog.repository.ReplyRepository; 13 | 14 | import lombok.RequiredArgsConstructor; 15 | 16 | @Service 17 | @RequiredArgsConstructor 18 | public class BoardService { 19 | 20 | private final BoardRepository boardRepository; 21 | private final ReplyRepository replyRepository; 22 | 23 | // public BoardService(BoardRepository bRepo, ReplyRepository rRepo) { 24 | // this.boardRepository = bRepo; 25 | // this.replyRepository = rRepo; 26 | // } 27 | 28 | @Transactional 29 | public void 글쓰기(Board board, User user) { // title, content 30 | board.setCount(0); 31 | board.setUser(user); 32 | boardRepository.save(board); 33 | } 34 | 35 | @Transactional(readOnly = true) 36 | public Page 글목록(Pageable pageable){ 37 | return boardRepository.findAll(pageable); 38 | } 39 | 40 | @Transactional(readOnly = true) 41 | public Board 글상세보기(int id) { 42 | return boardRepository.findById(id) 43 | .orElseThrow(()->{ 44 | return new IllegalArgumentException("글 상세보기 실패 : 아이디를 찾을 수 없습니다."); 45 | }); 46 | } 47 | 48 | @Transactional 49 | public void 글삭제하기(int id) { 50 | System.out.println("글삭제하기 : "+id); 51 | boardRepository.deleteById(id); 52 | } 53 | 54 | @Transactional 55 | public void 글수정하기(int id, Board requestBoard) { 56 | Board board = boardRepository.findById(id) 57 | .orElseThrow(()->{ 58 | return new IllegalArgumentException("글 찾기 실패 : 아이디를 찾을 수 없습니다."); 59 | }); // 영속화 완료 60 | board.setTitle(requestBoard.getTitle()); 61 | board.setContent(requestBoard.getContent()); 62 | // 해당 함수로 종료시(Service가 종료될 때) 트랜잭션이 종료됩니다. 이때 더티체킹 - 자동 업데이트가 됨. db flush 63 | } 64 | 65 | @Transactional 66 | public void 댓글쓰기(ReplySaveRequestDto replySaveRequestDto) { 67 | int result = replyRepository.mSave(replySaveRequestDto.getUserId(), replySaveRequestDto.getBoardId(), replySaveRequestDto.getContent()); 68 | System.out.println("BoardService : "+result); 69 | } 70 | 71 | @Transactional 72 | public void 댓글삭제(int replyId) { 73 | replyRepository.deleteById(replyId); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import com.cos.blog.model.RoleType; 9 | import com.cos.blog.model.User; 10 | import com.cos.blog.repository.UserRepository; 11 | 12 | // 스프링이 컴포넌트 스캔을 통해서 Bean에 등록을 해줌. IoC를 해준다. 13 | @Service 14 | public class UserService { 15 | 16 | @Autowired 17 | private UserRepository userRepository; 18 | 19 | @Autowired 20 | private BCryptPasswordEncoder encoder; 21 | 22 | @Transactional(readOnly = true) 23 | public User 회원찾기(String username) { 24 | User user = userRepository.findByUsername(username).orElseGet(()->{ 25 | return new User(); 26 | }); 27 | return user; 28 | } 29 | 30 | @Transactional 31 | public int 회원가입(User user) { 32 | String rawPassword = user.getPassword(); // 1234 원문 33 | String encPassword = encoder.encode(rawPassword); // 해쉬 34 | user.setPassword(encPassword); 35 | user.setRole(RoleType.USER); 36 | try { 37 | userRepository.save(user); 38 | return 1; 39 | } catch (Exception e) { 40 | return -1; 41 | } 42 | 43 | } 44 | 45 | @Transactional 46 | public void 회원수정(User user) { 47 | // 수정시에는 영속성 컨텍스트 User 오브젝트를 영속화시키고, 영속화된 User 오브젝트를 수정 48 | // select를 해서 User오브젝트를 DB로 부터 가져오는 이유는 영속화를 하기 위해서!! 49 | // 영속화된 오브젝트를 변경하면 자동으로 DB에 update문을 날려주거든요. 50 | User persistance = userRepository.findById(user.getId()).orElseThrow(()->{ 51 | return new IllegalArgumentException("회원 찾기 실패"); 52 | }); 53 | 54 | // Validate 체크 => oauth 필드에 값이 없으면 수정 가능 55 | if(persistance.getOauth() == null || persistance.getOauth().equals("")) { 56 | String rawPassword = user.getPassword(); 57 | String encPassword = encoder.encode(rawPassword); 58 | persistance.setPassword(encPassword); 59 | persistance.setEmail(user.getEmail()); 60 | } 61 | 62 | // 회원수정 함수 종료시 = 서비스 종료 = 트랜잭션 종료 = commit 이 자동으로 됩니다. 63 | // 영속화된 persistance 객체의 변화가 감지되면 더티체킹이 되어 update문을 날려줌. 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/BlogControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | // 스프링이 com.cos.blog 패키지 이하를 스캔해서 모든 파일을 메모리에 new하는 것은 아니구요. 7 | // 특정 어노테이션이 붙어있는 클래스 파일들을 new해서(IoC) 스프링 컨테이너에 관리해줍니다. 8 | @RestController 9 | public class BlogControllerTest { 10 | 11 | //http://localhost:8080/test/hello 12 | @GetMapping("/test/hello") 13 | public String hello() { 14 | return "hello spring boot"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/DummyControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import java.util.List; 4 | import java.util.function.Supplier; 5 | 6 | import javax.transaction.Transactional; 7 | 8 | //import java.util.function.Supplier; 9 | 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.dao.EmptyResultDataAccessException; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.Pageable; 14 | import org.springframework.data.domain.Sort; 15 | import org.springframework.data.web.PageableDefault; 16 | import org.springframework.web.bind.annotation.DeleteMapping; 17 | import org.springframework.web.bind.annotation.GetMapping; 18 | import org.springframework.web.bind.annotation.PathVariable; 19 | import org.springframework.web.bind.annotation.PostMapping; 20 | import org.springframework.web.bind.annotation.PutMapping; 21 | import org.springframework.web.bind.annotation.RequestBody; 22 | import org.springframework.web.bind.annotation.RestController; 23 | 24 | import com.cos.blog.model.RoleType; 25 | import com.cos.blog.model.User; 26 | import com.cos.blog.repository.UserRepository; 27 | 28 | // html파일이 아니라 data를 리턴해주는 controller = RestController 29 | @RestController 30 | public class DummyControllerTest { 31 | 32 | @Autowired // 의존성 주입(DI) 33 | private UserRepository userRepository; 34 | 35 | // save함수는 id를 전달하지 않으면 insert를 해주고 36 | // save함수는 id를 전달하면 해당 id에 대한 데이터가 있으면 update를 해주고 37 | // save함수는 id를 전달하면 해당 id에 대한 데이터가 없으면 insert를 해요. 38 | // email, password 39 | 40 | @DeleteMapping("/dummy/user/{id}") 41 | public String delete(@PathVariable int id) { 42 | try { 43 | userRepository.deleteById(id); 44 | } catch (EmptyResultDataAccessException e) { 45 | return "삭제에 실패하였습니다. 해당 id는 DB에 없습니다."; 46 | } 47 | 48 | return "삭제되었습니다. id : "+id; 49 | } 50 | 51 | @Transactional // 함수 종료시에 자동 commit 이 됨. 52 | @PutMapping("/dummy/user/{id}") 53 | public User updateUser(@PathVariable int id, @RequestBody User requestUser) { //json 데이터를 요청 => Java Object(MessageConverter의 Jackson라이브러리가 변환해서 받아줘요.) 54 | System.out.println("id : "+id); 55 | System.out.println("password : "+requestUser.getPassword()); 56 | System.out.println("email : "+requestUser.getEmail()); 57 | 58 | User user = userRepository.findById(id).orElseThrow(()->{ 59 | return new IllegalArgumentException("수정에 실패하였습니다."); 60 | }); 61 | user.setPassword(requestUser.getPassword()); 62 | //user.setEmail(requestUser.getEmail()); 63 | 64 | // userRepository.save(user); 65 | 66 | // 더티 체킹 67 | return user; 68 | } 69 | 70 | // http://localhost:8000/blog/dummy/user 71 | @GetMapping("/dummy/users") 72 | public List list(){ 73 | return userRepository.findAll(); 74 | } 75 | 76 | // 한페이지당 2건에 데이터를 리턴받아 볼 예정 77 | @GetMapping("/dummy/user") 78 | public Page pageList(@PageableDefault(size=2, sort="id", direction = Sort.Direction.DESC) Pageable pageable){ 79 | Page pagingUser = userRepository.findAll(pageable); 80 | 81 | List users = pagingUser.getContent(); 82 | return pagingUser; 83 | } 84 | 85 | // {id} 주소로 파마레터를 전달 받을 수 있음. 86 | // http://localhost:8000/blog/dummy/user/5 87 | @GetMapping("/dummy/user/{id}") 88 | public User detail(@PathVariable int id) { 89 | // user/4을 찾으면 내가 데이터베이스에서 못찾아오게 되면 user가 null이 될 것 아냐? 90 | // 그럼 return null 이 리턴이 되자나.. 그럼 프로그램에 문제가 있지 않겠니? 91 | // Optional로 너의 User객체를 감싸서 가져올테니 null인지 아닌지 판단해서 return해!! 92 | 93 | // // 람다식 94 | // User user = userRepository.findById(id).orElseThrow(()->{ 95 | // return new IllegalArgumentException("해당 사용자는 없습니다."); 96 | // }); 97 | 98 | User user = userRepository.findById(id).orElseThrow(new Supplier() { 99 | @Override 100 | public IllegalArgumentException get() { 101 | return new IllegalArgumentException("해당 사용자가 없습니다."); 102 | } 103 | }); 104 | // 요청 : 웹브라우저 105 | // user 객체 = 자바 오브젝트 106 | // 변환 ( 웹브라우저가 이해할 수 있는 데이터) -> json (Gson 라이브러리) 107 | // 스프링부트 = MessageConverter라는 애가 응답시에 자동 작동 108 | // 만약에 자바 오브젝트를 리턴하게 되면 MessageConverter가 Jackson 라이브러리를 호출해서 109 | // user 오브젝트를 json으로 변환해서 브라우저에게 던져줍니다. 110 | return user; 111 | } 112 | 113 | // http://localhost:8000/blog/dummy/join (요청) 114 | // http의 body에 username, password, email 데이터를 가지고 (요청) 115 | @PostMapping("/dummy/join") 116 | public String join(User user) { // key=value (약속된 규칙) 117 | System.out.println("id : "+user.getId()); 118 | System.out.println("username : "+user.getUsername()); 119 | System.out.println("password : "+user.getPassword()); 120 | System.out.println("email : "+user.getEmail()); 121 | System.out.println("role : "+user.getRole()); 122 | System.out.println("createDate : "+user.getCreateDate()); 123 | 124 | user.setRole(RoleType.USER); 125 | userRepository.save(user); 126 | return "회원가입이 완료되었습니다."; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/HttpControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import org.springframework.web.bind.annotation.DeleteMapping; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PostMapping; 6 | import org.springframework.web.bind.annotation.PutMapping; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | // 사용자가 요청 -> 응답(HTML 파일) 11 | // @Controller 12 | 13 | // 사용자가 요청 -> 응답(Data) 14 | @RestController 15 | public class HttpControllerTest { 16 | 17 | private static final String TAG = "HttpControllerTest : "; 18 | 19 | // localhost:8000/blog/http/lombok 20 | @GetMapping("/http/lombok") 21 | public String lombokTest() { 22 | Member m = Member.builder().username("ssar").password("1234").email("ssar@nate.com").build(); 23 | System.out.println(TAG+"getter : "+m.getUsername()); 24 | m.setUsername("cos"); 25 | System.out.println(TAG+"setter : "+m.getUsername()); 26 | return "lombok test 완료"; 27 | } 28 | 29 | 30 | // 인터넷 브라우저 요청은 무조건 get요청밖에 할 수 없다. 31 | // http://localhost:8080/http/get (select) 32 | @GetMapping("/http/get") 33 | public String getTest(Member m) { //id=1&username=ssar&password=1234&email=ssar@nate.com // MessageConverter (스프링부트) 34 | return "get 요청 : "+m.getId()+", "+m.getUsername()+", "+m.getPassword()+", "+m.getEmail(); 35 | } 36 | 37 | // http://localhost:8080/http/post (insert) 38 | @PostMapping("/http/post") // text/plain, application/json 39 | public String postTest(@RequestBody Member m) { // MessageConverter (스프링부트) 40 | return "post 요청 : "+m.getId()+", "+m.getUsername()+", "+m.getPassword()+", "+m.getEmail(); 41 | } 42 | 43 | // http://localhost:8080/http/put (update) 44 | @PutMapping("/http/put") 45 | public String putTest(@RequestBody Member m) { 46 | return "put 요청 : "+m.getId()+", "+m.getUsername()+", "+m.getPassword()+", "+m.getEmail(); 47 | } 48 | 49 | // http://localhost:8080/http/delete (delete) 50 | @DeleteMapping("/http/delete") 51 | public String deleteTest() { 52 | return "delete 요청"; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/Member.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @NoArgsConstructor 10 | public class Member { 11 | private int id; 12 | private String username; 13 | private String password; 14 | private String email; 15 | 16 | @Builder 17 | public Member(int id, String username, String password, String email) { 18 | this.id = id; 19 | this.username = username; 20 | this.password = password; 21 | this.email = email; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/ReplyControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import com.cos.blog.model.Board; 11 | import com.cos.blog.model.Reply; 12 | import com.cos.blog.repository.BoardRepository; 13 | import com.cos.blog.repository.ReplyRepository; 14 | 15 | @RestController 16 | public class ReplyControllerTest { 17 | 18 | @Autowired 19 | private BoardRepository boardRepository; 20 | 21 | @Autowired 22 | private ReplyRepository replyRepository; 23 | 24 | @GetMapping("/test/board/{id}") 25 | public Board getBoard(@PathVariable int id) { 26 | return boardRepository.findById(id).get(); // jackson 라이브러리 (오브젝트를 json으로 리턴) => 모델의 getter를 호출 27 | } 28 | 29 | @GetMapping("/test/reply") 30 | public List getReply() { 31 | return replyRepository.findAll(); // jackson 라이브러리 (오브젝트를 json으로 리턴) => 모델의 getter를 호출 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/cos/blog/test/TempControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.cos.blog.test; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | @Controller 7 | public class TempControllerTest { 8 | 9 | // http://localhost:8000/blog/temp/home 10 | @GetMapping("/temp/home") 11 | public String tempHome() { 12 | System.out.println("tempHome()"); 13 | // 파일리턴 기본경로 : src/main/resources/static 14 | // 리턴명 : /home.html 15 | // 풀경로 : src/main/resources/static/home.html 16 | return "/home.html"; 17 | } 18 | 19 | @GetMapping("/temp/img") 20 | public String tempImg() { 21 | return "/a.png"; 22 | } 23 | 24 | @GetMapping("/temp/jsp") 25 | public String tempJsp() { 26 | // prefix : /WEB-INF/views/ 27 | // suffix : .jsp 28 | // 풀네임 : /WEB-INF/views/test.jsp 29 | 30 | return "test"; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8000 3 | servlet: 4 | context-path: / 5 | 6 | spring: 7 | mvc: 8 | view: 9 | prefix: /WEB-INF/views/ 10 | suffix: .jsp 11 | 12 | datasource: 13 | driver-class-name: com.mysql.cj.jdbc.Driver 14 | url: jdbc:mysql://localhost:3306/blog?serverTimezone=Asia/Seoul 15 | username: cos 16 | password: cos1234 17 | 18 | jpa: 19 | open-in-view: true 20 | hibernate: 21 | ddl-auto: update 22 | naming: 23 | physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 24 | use-new-id-generator-mappings: false 25 | #show-sql: true 26 | properties: 27 | hibernate.format_sql: true 28 | 29 | jackson: 30 | serialization: 31 | fail-on-empty-beans: false 32 | 33 | cos: 34 | key: cos1234 -------------------------------------------------------------------------------- /src/main/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8000 3 | 4 | spring: 5 | mvc: 6 | view: 7 | prefix: /WEB-INF/views/ 8 | suffix: .jsp 9 | 10 | datasource: 11 | url: jdbc:h2:mem:test;MODE=MySQL 12 | driver-class-name: org.h2.Driver 13 | username: sa 14 | password: 15 | h2: 16 | console: 17 | enabled: true 18 | 19 | jpa: 20 | open-in-view: true 21 | hibernate: 22 | ddl-auto: create 23 | naming: 24 | physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 25 | use-new-id-generator-mappings: false 26 | #show-sql: true 27 | properties: 28 | hibernate.format_sql: true 29 | 30 | jackson: 31 | serialization: 32 | fail-on-empty-beans: false 33 | 34 | cos: 35 | key: cos1234 -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: dev -------------------------------------------------------------------------------- /src/main/resources/static/image/kakao_login_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codingspecialist/Springboot-JPA-Blog/05e9ba257d908f7b09f518a46b251e4d390f63e3/src/main/resources/static/image/kakao_login_button.png -------------------------------------------------------------------------------- /src/main/resources/static/js/board.js: -------------------------------------------------------------------------------- 1 | let index = { 2 | init: function(){ 3 | $("#btn-save").on("click", ()=>{ 4 | this.save(); 5 | }); 6 | $("#btn-delete").on("click", ()=>{ 7 | this.deleteById(); 8 | }); 9 | $("#btn-update").on("click", ()=>{ 10 | this.update(); 11 | }); 12 | $("#btn-reply-save").on("click", ()=>{ 13 | this.replySave(); 14 | }); 15 | }, 16 | 17 | save: function(){ 18 | let data = { 19 | title: $("#title").val(), 20 | content: $("#content").val() 21 | }; 22 | 23 | $.ajax({ 24 | type: "POST", 25 | url: "/api/board", 26 | data: JSON.stringify(data), 27 | contentType: "application/json; charset=utf-8", 28 | dataType: "json" 29 | }).done(function(resp){ 30 | alert("글쓰기가 완료되었습니다."); 31 | location.href = "/"; 32 | }).fail(function(error){ 33 | alert(JSON.stringify(error)); 34 | }); 35 | }, 36 | 37 | deleteById: function(){ 38 | let id = $("#id").text(); 39 | 40 | $.ajax({ 41 | type: "DELETE", 42 | url: "/api/board/"+id, 43 | dataType: "json" 44 | }).done(function(resp){ 45 | alert("삭제가 완료되었습니다."); 46 | location.href = "/"; 47 | }).fail(function(error){ 48 | alert(JSON.stringify(error)); 49 | }); 50 | }, 51 | 52 | update: function(){ 53 | let id = $("#id").val(); 54 | 55 | let data = { 56 | title: $("#title").val(), 57 | content: $("#content").val() 58 | }; 59 | 60 | $.ajax({ 61 | type: "PUT", 62 | url: "/api/board/"+id, 63 | data: JSON.stringify(data), 64 | contentType: "application/json; charset=utf-8", 65 | dataType: "json" 66 | }).done(function(resp){ 67 | alert("글수정이 완료되었습니다."); 68 | location.href = "/"; 69 | }).fail(function(error){ 70 | alert(JSON.stringify(error)); 71 | }); 72 | }, 73 | 74 | replySave: function(){ 75 | let data = { 76 | userId: $("#userId").val(), 77 | boardId: $("#boardId").val(), 78 | content: $("#reply-content").val() 79 | }; 80 | 81 | $.ajax({ 82 | type: "POST", 83 | url: `/api/board/${data.boardId}/reply`, 84 | data: JSON.stringify(data), 85 | contentType: "application/json; charset=utf-8", 86 | dataType: "json" 87 | }).done(function(resp){ 88 | alert("댓글작성이 완료되었습니다."); 89 | location.href = `/board/${data.boardId}`; 90 | }).fail(function(error){ 91 | alert(JSON.stringify(error)); 92 | }); 93 | }, 94 | 95 | replyDelete : function(boardId, replyId){ 96 | $.ajax({ 97 | type: "DELETE", 98 | url: `/api/board/${boardId}/reply/${replyId}`, 99 | dataType: "json" 100 | }).done(function(resp){ 101 | alert("댓글삭제 성공"); 102 | location.href = `/board/${boardId}`; 103 | }).fail(function(error){ 104 | alert(JSON.stringify(error)); 105 | }); 106 | }, 107 | } 108 | 109 | index.init(); 110 | -------------------------------------------------------------------------------- /src/main/resources/static/js/user.js: -------------------------------------------------------------------------------- 1 | let index = { 2 | init: function(){ 3 | $("#btn-save").on("click", ()=>{ // function(){} , ()=>{} this를 바인딩하기 위해서!! 4 | this.save(); 5 | }); 6 | $("#btn-update").on("click", ()=>{ // function(){} , ()=>{} this를 바인딩하기 위해서!! 7 | this.update(); 8 | }); 9 | }, 10 | 11 | save: function(){ 12 | //alert('user의 save함수 호출됨'); 13 | let data = { 14 | username: $("#username").val(), 15 | password: $("#password").val(), 16 | email: $("#email").val() 17 | }; 18 | 19 | //console.log(data); 20 | 21 | // ajax호출시 default가 비동기 호출 22 | // ajax 통신을 이용해서 3개의 데이터를 json으로 변경하여 insert 요청!! 23 | // ajax가 통신을 성공하고 서버가 json을 리턴해주면 자동으로 자바 오브젝트로 변환해주네요. 24 | $.ajax({ 25 | type: "POST", 26 | url: "/auth/joinProc", 27 | data: JSON.stringify(data), // http body데이터 28 | contentType: "application/json; charset=utf-8",// body데이터가 어떤 타입인지(MIME) 29 | dataType: "json" // 요청을 서버로해서 응답이 왔을 때 기본적으로 모든 것이 문자열 (생긴게 json이라면) => javascript오브젝트로 변경 30 | }).done(function(resp){ 31 | if(resp.status === 500){ 32 | alert("회원가입에 실패하였습니다."); 33 | }else{ 34 | alert("회원가입이 완료되었습니다."); 35 | location.href = "/"; 36 | } 37 | 38 | }).fail(function(error){ 39 | alert(JSON.stringify(error)); 40 | }); 41 | 42 | }, 43 | 44 | update: function(){ 45 | //alert('user의 save함수 호출됨'); 46 | let data = { 47 | id: $("#id").val(), 48 | username: $("#username").val(), 49 | password: $("#password").val(), 50 | email: $("#email").val() 51 | }; 52 | 53 | $.ajax({ 54 | type: "PUT", 55 | url: "/user", 56 | data: JSON.stringify(data), // http body데이터 57 | contentType: "application/json; charset=utf-8",// body데이터가 어떤 타입인지(MIME) 58 | dataType: "json" // 요청을 서버로해서 응답이 왔을 때 기본적으로 모든 것이 문자열 (생긴게 json이라면) => javascript오브젝트로 변경 59 | }).done(function(resp){ 60 | alert("회원수정이 완료되었습니다."); 61 | //console.log(resp); 62 | location.href = "/"; 63 | }).fail(function(error){ 64 | alert(JSON.stringify(error)); 65 | }); 66 | 67 | }, 68 | } 69 | 70 | index.init(); 71 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/board/detail.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | <%@ include file="../layout/header.jsp"%> 4 | 5 | 6 | 돌아가기 7 | 8 | 9 | 수정 10 | 삭제 11 | 12 | 13 | 14 | 글 번호 : ${board.id} 작성자 : ${board.user.username} 15 | 16 | 17 | 18 | ${board.title} 19 | 20 | 21 | 22 | ${board.content} 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 36 | 37 | 38 | 39 | 40 | 댓글 리스트 41 | 42 | 43 | 44 | 45 | ${reply.content} 46 | 47 | 작성자 : ${reply.user.username} 48 | 49 | 삭제 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | <%@ include file="../layout/footer.jsp"%> 61 | 62 | 63 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/board/saveForm.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | <%@ include file="../layout/header.jsp"%> 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 글쓰기완료 17 | 18 | 19 | 25 | 26 | <%@ include file="../layout/footer.jsp"%> 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/board/updateForm.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | <%@ include file="../layout/header.jsp"%> 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | ${board.content} 15 | 16 | 17 | 글수정완료 18 | 19 | 20 | 26 | 27 | <%@ include file="../layout/footer.jsp"%> 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | <%@ include file="layout/header.jsp"%> 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${board.title} 11 | 상세보기 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Previous 20 | 21 | 22 | Previous 23 | 24 | 25 | 26 | 27 | 28 | Next 29 | 30 | 31 | Next 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | <%@ include file="layout/footer.jsp"%> 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/layout/footer.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | 4 | Created by Cos 5 | 📞 010-2222-7777 6 | 🏴 부산 수영구 XX동 7 | 8 | 9 |
Created by Cos
📞 010-2222-7777
🏴 부산 수영구 XX동