diff --git "a/pdf/Springboot\345\205\245\351\227\250\345\210\260\347\262\276\351\200\232\357\274\210\350\266\205\350\257\246\347\273\206\346\226\207\346\241\243\357\274\211_springboot\346\226\207\346\241\243-CSDN\345\215\232\345\256\242.pdf" "b/pdf/Springboot\345\205\245\351\227\250\345\210\260\347\262\276\351\200\232\357\274\210\350\266\205\350\257\246\347\273\206\346\226\207\346\241\243\357\274\211_springboot\346\226\207\346\241\243-CSDN\345\215\232\345\256\242.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..d23656af6b9c5cb1c15dc612ff85d1e01897c474 Binary files /dev/null and "b/pdf/Springboot\345\205\245\351\227\250\345\210\260\347\262\276\351\200\232\357\274\210\350\266\205\350\257\246\347\273\206\346\226\207\346\241\243\357\274\211_springboot\346\226\207\346\241\243-CSDN\345\215\232\345\256\242.pdf" differ diff --git a/springboot-aop-new/.gitignore b/springboot-aop-new/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..82eca336e352c9026decda294ff678968050edfc --- /dev/null +++ b/springboot-aop-new/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/springboot-aop-new/.mvn/wrapper/maven-wrapper.jar b/springboot-aop-new/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9cc84ea9b4d95453115d0c26488d6a78694e0bc6 Binary files /dev/null and b/springboot-aop-new/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-aop-new/.mvn/wrapper/maven-wrapper.properties b/springboot-aop-new/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..b573bb50d56e8c19282593cbf5b081e211923a83 --- /dev/null +++ b/springboot-aop-new/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/springboot-aop-new/mvnw b/springboot-aop-new/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..5bf251c0774593ca4f5335acf0f7483eaa162e8f --- /dev/null +++ b/springboot-aop-new/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-aop-new/mvnw.cmd b/springboot-aop-new/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..019bd74d766ebd4c033528112148d866555b5c9e --- /dev/null +++ b/springboot-aop-new/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-aop-new/pom.xml b/springboot-aop-new/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..87cf1a0a2081438765abf779962403c67f7c5633 --- /dev/null +++ b/springboot-aop-new/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.itcodai + course09 + 0.0.1-SNAPSHOT + jar + + course09 + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-aop + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/springboot-aop-new/src/main/java/com/itcodai/course09/Course09Application.java b/springboot-aop-new/src/main/java/com/itcodai/course09/Course09Application.java new file mode 100644 index 0000000000000000000000000000000000000000..9addf2d05f84b2a6c1c4fef8b8cb40763d998ddd --- /dev/null +++ b/springboot-aop-new/src/main/java/com/itcodai/course09/Course09Application.java @@ -0,0 +1,12 @@ +package com.itcodai.course09; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Course09Application { + + public static void main(String[] args) { + SpringApplication.run(Course09Application.class, args); + } +} diff --git a/springboot-aop-new/src/main/java/com/itcodai/course09/controller/AopController.java b/springboot-aop-new/src/main/java/com/itcodai/course09/controller/AopController.java new file mode 100644 index 0000000000000000000000000000000000000000..cbe1c90b4dfdfbbc0c5efd5468de590b2704e173 --- /dev/null +++ b/springboot-aop-new/src/main/java/com/itcodai/course09/controller/AopController.java @@ -0,0 +1,22 @@ +package com.itcodai.course09.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/aop") +public class AopController { + + @GetMapping("/{name}") + public String testAop(@PathVariable String name) { + return "Hello " + name; + } + + @GetMapping("/exception") + public String testException() { + int i = 1 / 0; + return "success"; + } +} diff --git a/springboot-aop-new/src/main/java/com/itcodai/course09/handler/LogAspectHandler.java b/springboot-aop-new/src/main/java/com/itcodai/course09/handler/LogAspectHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..88dcf3f313cb82e9f895ef769a88d925860993b7 --- /dev/null +++ b/springboot-aop-new/src/main/java/com/itcodai/course09/handler/LogAspectHandler.java @@ -0,0 +1,93 @@ +package com.itcodai.course09.handler; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +@Aspect +@Component +public class LogAspectHandler { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** + * 定义一个切面,拦截com.itcodai.course09.controller包下的所有方法 + */ + @Pointcut("execution(* com.itcodai.course09.controller..*.*(..))") + public void pointCut() {} + + /** + * 在上面定义的切面方法之前执行该方法 + * @param joinPoint jointPoint + */ + @Before("pointCut()") + public void doBefore(JoinPoint joinPoint) { + logger.info("====doBefore方法进入了===="); + + // 获取签名 + Signature signature = joinPoint.getSignature(); + // 获取切入的包名 + String declaringTypeName = signature.getDeclaringTypeName(); + // 获取即将执行的方法名 + String funcName = signature.getName(); + logger.info("即将执行方法为: {},属于{}包", funcName, declaringTypeName); + + // 也可以用来记录一些信息,比如获取请求的url和ip + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + // 获取请求url + String url = request.getRequestURL().toString(); + // 获取请求ip + String ip = request.getRemoteAddr(); + logger.info("用户请求的url为:{},ip地址为:{}", url, ip); + } + + /** + * 在上面定义的切面方法之后执行该方法 + * @param joinPoint jointPoint + */ + @After("pointCut()") + public void doAfter(JoinPoint joinPoint) { + + logger.info("====doAfter方法进入了===="); + Signature signature = joinPoint.getSignature(); + String method = signature.getName(); + logger.info("方法{}已经执行完", method); + } + + /** + * 在上面定义的切面方法返回后执行该方法,可以捕获返回对象或者对返回对象进行增强 + * @param joinPoint joinPoint + * @param result result + */ + @AfterReturning(pointcut = "pointCut()", returning = "result") + public void doAfterReturning(JoinPoint joinPoint, Object result) { + + Signature signature = joinPoint.getSignature(); + String classMethod = signature.getName(); + logger.info("方法{}执行完毕,返回参数为:{}", classMethod, result); + // 实际项目中可以根据业务做具体的返回值增强 + logger.info("对返回参数进行业务上的增强:{}", result + "增强版"); + } + + /** + * 在上面定义的切面方法执行抛异常时,执行该方法 + * @param joinPoint jointPoint + * @param ex ex + */ + @AfterThrowing(pointcut = "pointCut()", throwing = "ex") + public void afterThrowing(JoinPoint joinPoint, Throwable ex) { + Signature signature = joinPoint.getSignature(); + String method = signature.getName(); + // 处理异常的逻辑 + logger.info("执行方法{}出错,异常为:{}", method, ex.getMessage()); + } + +} diff --git a/springboot-aop-new/src/main/resources/application.properties b/springboot-aop-new/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/springboot-aop-new/src/test/java/com/itcodai/course09/Course09ApplicationTests.java b/springboot-aop-new/src/test/java/com/itcodai/course09/Course09ApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..9680c7510d95ff942bddb8ffe1ea554b7a5abbfb --- /dev/null +++ b/springboot-aop-new/src/test/java/com/itcodai/course09/Course09ApplicationTests.java @@ -0,0 +1,16 @@ +package com.itcodai.course09; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Course09ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/springboot-aop/README.md b/springboot-aop/README.md index c1187c0b9f6bb57b590f5b4b1e1be1a5af3f1d00..8c541db45711e4e3fcb6dafba50b74f49fcb275f 100644 --- a/springboot-aop/README.md +++ b/springboot-aop/README.md @@ -18,6 +18,14 @@ AOP工作重点: 1. 如何通过切点(Pointcut)和增强(Advice)定位到连接点(Jointpoint)上; 2. 如何在增强(Advice)中编写切面的代码。 +excution表达式用法介绍: +以 execution(* com.itcodai.course09.controller..*.*(..))) 表达式为例: +execution() 为表达式主体 +第一个 * 号的位置:表示返回值类型,* 表示所有类型 +包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com.itcodai.course09.controller 包、子包下所有类的方法 +第二个 * 号的位置:表示类名,* 表示所有类 +*(..) :这个星号表示方法名,* 表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数 + ## 许可证 Copyright (c) 2018 Xiong Neng diff --git a/springboot-aop/src/main/java/com/xncoding/Application.java b/springboot-aop/src/main/java/com/xncoding/Application.java index 2a00aacf42e153a2b0494ba03d39d27aab663c98..daf6679571c3c8eba93e61ae80df1ab4a9eb7a05 100644 --- a/springboot-aop/src/main/java/com/xncoding/Application.java +++ b/springboot-aop/src/main/java/com/xncoding/Application.java @@ -1,12 +1,35 @@ package com.xncoding; +import com.xncoding.po.Student; +import com.xncoding.po.User; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.servlet.support.JstlUtils; + +import javax.annotation.Resource; @SpringBootApplication public class Application { + public static void main(String[] args) { - SpringApplication.run(Application.class, args); + ConfigurableApplicationContext run = SpringApplication.run(Application.class, args); + String[] beanDefinitionNames = run.getBeanDefinitionNames(); + for (int i = 0; i < beanDefinitionNames.length; i++) { +// System.out.println("定义的bean的名称为:"+beanDefinitionNames[i]); + } + + User aaa = (User)run.getBean("aaa"); + User bbb = run.getBean(User.class); + + Student bean = (Student)run.getBean(Student.class); + +// System.out.println(aaa.toString()); +// System.out.println(aaa == bbb); + + System.out.println("student:"+ bean); + + System.err.println("红色字体显示!"); } } diff --git a/springboot-aop/src/main/java/com/xncoding/aop/aspect/UserAccessAspect.java b/springboot-aop/src/main/java/com/xncoding/aop/aspect/UserAccessAspect.java index 91cdeddf8685ead455d3dd2cbcf478f800921696..f19b7ff031c2d3480779f9625f3b62f891458403 100644 --- a/springboot-aop/src/main/java/com/xncoding/aop/aspect/UserAccessAspect.java +++ b/springboot-aop/src/main/java/com/xncoding/aop/aspect/UserAccessAspect.java @@ -3,8 +3,12 @@ package com.xncoding.aop.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Component; +import java.lang.reflect.Method; + @Component @Aspect public class UserAccessAspect { @@ -19,6 +23,7 @@ public class UserAccessAspect { System.out.println("second before"); } +// @Around("@annotation(userAccess)") @Around("@annotation(userAccess)") public Object around(ProceedingJoinPoint pjp, UserAccess userAccess) { //获取注解里的值 @@ -30,4 +35,26 @@ public class UserAccessAspect { return null; } } + + /** + * 这种写法与上面的写法是一个效果,不过需要在里面手动获取注解,上面的写法是直接通过参数匹配获取到注解进行操作 + * @param pjp + * @return + */ + @Around("access()") + public Object around(ProceedingJoinPoint pjp) { + // 获取注解所在的目标方法 + Method method = ((MethodSignature) pjp.getSignature()).getMethod(); + // 获取方法上注解 + UserAccess annotation = method.getAnnotation(UserAccess.class); + + //获取注解里的值 + System.out.println("second around:" + annotation.desc()); + try { + return pjp.proceed(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + return null; + } + } } \ No newline at end of file diff --git a/springboot-aop/src/main/java/com/xncoding/aop/controller/UserController.java b/springboot-aop/src/main/java/com/xncoding/aop/controller/UserController.java index eb1f76431f887312d822836a880ff83573a14be1..2b0f386dcb40cbc31011754d4e36014bf4a36bb2 100644 --- a/springboot-aop/src/main/java/com/xncoding/aop/controller/UserController.java +++ b/springboot-aop/src/main/java/com/xncoding/aop/controller/UserController.java @@ -9,6 +9,7 @@ import com.xncoding.aop.aspect.UserAccess; * Description: */ @RestController +@UserAccess(desc = "class上的注解") public class UserController { @RequestMapping("/first") public Object first() { diff --git a/springboot-aop/src/main/java/com/xncoding/component/Listeners.java b/springboot-aop/src/main/java/com/xncoding/component/Listeners.java new file mode 100644 index 0000000000000000000000000000000000000000..d59c8f2b6f4b8e0ed6e0439defd1923c10edf074 --- /dev/null +++ b/springboot-aop/src/main/java/com/xncoding/component/Listeners.java @@ -0,0 +1,11 @@ +package com.xncoding.component; + +import org.springframework.stereotype.Component; + +@Component +public class Listeners { + + public void testMsg(){ + System.out.println("初始化的时候方法已经被调用了!"); + } +} diff --git a/springboot-aop/src/main/java/com/xncoding/config/AppConfig.java b/springboot-aop/src/main/java/com/xncoding/config/AppConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..3d93db0871487339198356c3bd37dd10a048aaa7 --- /dev/null +++ b/springboot-aop/src/main/java/com/xncoding/config/AppConfig.java @@ -0,0 +1,39 @@ +package com.xncoding.config; + +import com.xncoding.interceptor.AppInterceptor; +import com.xncoding.po.User; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class AppConfig implements WebMvcConfigurer { + + /** + * 注册拦截器 + * .addPathPatterns("/**"):表示拦截整个应用中的所有请求 + * .excludePathPatterns(String... patterns):表示排除这些规则的请求,不对它们进行拦截 + *

+ * spring Boot 2 以后,静态资源也会被拦截. + * classpath:/META‐INF/resources/","classpath:/resources/","classpath:/static/","classpath:/public/"下的资源也会被拦截 + * 通常静态资源可以不需要进行拦截,可以对它们直接进行放行 + * + * @param registry + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + + registry.addInterceptor(new AppInterceptor()) + .addPathPatterns("/**") + .excludePathPatterns("/first") + .excludePathPatterns("/webjars/**", "/css/**/*.css", "/js/**/*.js", "/fonts/**", "/images/**"); + } + + @Bean + public User aaa(){ + return new User(); + } + + +} diff --git a/springboot-aop/src/main/java/com/xncoding/interceptor/AppInterceptor.java b/springboot-aop/src/main/java/com/xncoding/interceptor/AppInterceptor.java new file mode 100644 index 0000000000000000000000000000000000000000..b0594164206abc7d73cfc1a5fadc2d7b89e1fc5a --- /dev/null +++ b/springboot-aop/src/main/java/com/xncoding/interceptor/AppInterceptor.java @@ -0,0 +1,60 @@ +package com.xncoding.interceptor; + +import com.xncoding.aop.aspect.UserAccess; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class AppInterceptor implements HandlerInterceptor { + + /** + * 请求进入时进行拦截,返回 true 时,表示继续往下走; + * 返回 false 时, 表示停止后续的执行,即请求不会到达控制层. + * + * @param request + * @param response + * @param handler + * @return + * @throws Exception + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + StringBuffer requestURL = request.getRequestURL(); + System.out.println("进入拦截器,用户请求:" + requestURL); + if (handler instanceof HandlerMethod) { + //方法处理器, 请求的目标方法 + HandlerMethod handlerMethod = (HandlerMethod) handler; + + //1: 获取目标方法上的指定注解,不存在时,返回 Null. + UserAccess methodOperate = handlerMethod.getMethodAnnotation(UserAccess.class); + if (methodOperate != null) { + String desc = methodOperate.desc(); + System.out.println("\t目标方法存在 @MethodOperate 注解, desc=" + desc); + } + + //2: 获取目标方法所在类上的指定主键, 不存在时, 返回 null. + UserAccess classOperate = handlerMethod.getMethod().getDeclaringClass().getAnnotation(UserAccess.class); + if (classOperate != null) { + String desc = classOperate.desc(); + System.out.println("\t目标方法所在的类存在 @ClassOperate 注解, desc=" + desc); + } + + // 3、获取目标方法及其类上的注解 + UserAccess multipleOperate1 = handlerMethod.getMethodAnnotation(UserAccess.class); + UserAccess multipleOperate2 = handlerMethod.getMethod().getDeclaringClass().getAnnotation(UserAccess.class); + if (multipleOperate1 != null) { + String desc = multipleOperate1.desc(); + + System.out.println("\t目标方法存在 @MultipleOperate 注解, desc=" + desc); + } + if (multipleOperate2 != null) { + String desc = multipleOperate2.desc(); + + System.out.println("\t目标方法所在的类存在 @MultipleOperate 注解, desc=" + desc); + } + } + return true; + } +} diff --git a/springboot-aop/src/main/java/com/xncoding/po/Student.java b/springboot-aop/src/main/java/com/xncoding/po/Student.java new file mode 100644 index 0000000000000000000000000000000000000000..5997b9407cf3c8a3c8d3a20a9c803db375feb713 --- /dev/null +++ b/springboot-aop/src/main/java/com/xncoding/po/Student.java @@ -0,0 +1,37 @@ +package com.xncoding.po; + +import org.springframework.stereotype.Component; + +@Component +public class Student { + + private String stuName; + + private String stuNo; + + private String stuClass; + + public String getStuName() { + return stuName; + } + + public void setStuName(String stuName) { + this.stuName = stuName; + } + + public String getStuNo() { + return stuNo; + } + + public void setStuNo(String stuNo) { + this.stuNo = stuNo; + } + + public String getStuClass() { + return stuClass; + } + + public void setStuClass(String stuClass) { + this.stuClass = stuClass; + } +} diff --git a/springboot-aop/src/main/java/com/xncoding/po/User.java b/springboot-aop/src/main/java/com/xncoding/po/User.java new file mode 100644 index 0000000000000000000000000000000000000000..ff950636bf45067459dc18dd8ff8b1e49e424c11 --- /dev/null +++ b/springboot-aop/src/main/java/com/xncoding/po/User.java @@ -0,0 +1,34 @@ +package com.xncoding.po; + +public class User { + + private Integer keyId; + + private String name; + + private String addr; + + public Integer getKeyId() { + return keyId; + } + + public void setKeyId(Integer keyId) { + this.keyId = keyId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } +} diff --git a/springboot-exception/.gitignore b/springboot-exception/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..82eca336e352c9026decda294ff678968050edfc --- /dev/null +++ b/springboot-exception/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/springboot-exception/.mvn/wrapper/maven-wrapper.jar b/springboot-exception/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9cc84ea9b4d95453115d0c26488d6a78694e0bc6 Binary files /dev/null and b/springboot-exception/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-exception/.mvn/wrapper/maven-wrapper.properties b/springboot-exception/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..b573bb50d56e8c19282593cbf5b081e211923a83 --- /dev/null +++ b/springboot-exception/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/springboot-exception/README.MD b/springboot-exception/README.MD new file mode 100644 index 0000000000000000000000000000000000000000..b576b22784f7f174260102b3d937deb593020cc5 --- /dev/null +++ b/springboot-exception/README.MD @@ -0,0 +1 @@ +见pdf中第八课 \ No newline at end of file diff --git a/springboot-exception/mvnw b/springboot-exception/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..5bf251c0774593ca4f5335acf0f7483eaa162e8f --- /dev/null +++ b/springboot-exception/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-exception/mvnw.cmd b/springboot-exception/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..019bd74d766ebd4c033528112148d866555b5c9e --- /dev/null +++ b/springboot-exception/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-exception/pom.xml b/springboot-exception/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..275b9bf0fa36cd609fd266c074f106fa7d353372 --- /dev/null +++ b/springboot-exception/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.itcodai + course08 + 0.0.1-SNAPSHOT + jar + + course08 + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/springboot-exception/src/main/java/com/itcodai/course08/Course08Application.java b/springboot-exception/src/main/java/com/itcodai/course08/Course08Application.java new file mode 100644 index 0000000000000000000000000000000000000000..38a5cf9d2507b9fa6db9259b10f2eb38941110f9 --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/Course08Application.java @@ -0,0 +1,12 @@ +package com.itcodai.course08; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Course08Application { + + public static void main(String[] args) { + SpringApplication.run(Course08Application.class, args); + } +} diff --git a/springboot-exception/src/main/java/com/itcodai/course08/controller/ExceptionController.java b/springboot-exception/src/main/java/com/itcodai/course08/controller/ExceptionController.java new file mode 100644 index 0000000000000000000000000000000000000000..f056f3497f6fd4829355e6cfeca6bc44468a0fa5 --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/controller/ExceptionController.java @@ -0,0 +1,41 @@ +package com.itcodai.course08.controller; + +import com.itcodai.course08.entity.JsonResult; +import com.itcodai.course08.exception.BusinessErrorException; +import com.itcodai.course08.exception.BusinessMsgEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/exception") +public class ExceptionController { + + private static final Logger logger = LoggerFactory.getLogger(ExceptionController.class); + + @GetMapping("/null/point/exception") + public JsonResult testNullPointException() { + String str = null; + str.length(); + return new JsonResult(); + } + + @PostMapping("/test") + public JsonResult test(@RequestParam("name") String name, + @RequestParam("pass") String pass) { + + logger.info("name:{}", name); + logger.info("pass:{}", pass); + return new JsonResult(); + } + + @GetMapping("/business") + public JsonResult testException() { + try { + int i = 1 / 0; + } catch (Exception e) { + throw new BusinessErrorException(BusinessMsgEnum.UNEXPECTED_EXCEPTION); + } + return new JsonResult(); + } +} diff --git a/springboot-exception/src/main/java/com/itcodai/course08/entity/JsonResult.java b/springboot-exception/src/main/java/com/itcodai/course08/entity/JsonResult.java new file mode 100644 index 0000000000000000000000000000000000000000..49ebfbc46f06b133aefb61b9d4845f03753d0672 --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/entity/JsonResult.java @@ -0,0 +1,54 @@ +package com.itcodai.course08.entity; + +/** + * 统一返回的异常封装实体 + */ +public class JsonResult { + + /** + * 异常码 + */ + protected String code; + + /** + * 异常信息 + */ + protected String msg; + + public JsonResult() { + this.code = "200"; + this.msg = "操作成功"; + } + + public JsonResult(String code, String msg) { + this.code = code; + this.msg = msg; + } + +// public JsonResult(BusinessErrorException ex) { +// this.code = ex.getCode(); +// this.msg = ex.getMessage(); +// } +// +// public JsonResult(BusinessMsgEnum msg) { +// this.code = msg.code(); +// this.msg = msg.msg(); +// } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessErrorException.java b/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessErrorException.java new file mode 100644 index 0000000000000000000000000000000000000000..c63db140f8bb85bd140011141b3b6d7ad8aca19f --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessErrorException.java @@ -0,0 +1,54 @@ +/* + * + * Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved. + * + * FileName:BusinessErrorException.java + * + * Description: + * + * History: + * Version Author Date Operation + * 1.0 lli 2017年8月2日下午5:30:56 Create + */ +package com.itcodai.course08.exception; + +/** + * 自定义业务异常 + * @author shengwu ni + */ +public class BusinessErrorException extends RuntimeException { + + private static final long serialVersionUID = -7480022450501760611L; + + /** + * 异常码 + */ + private String code; + + /** + * 异常提示信息 + */ + private String message; + + public BusinessErrorException(BusinessMsgEnum businessMsgEnum) { + this.code = businessMsgEnum.code(); + this.message = businessMsgEnum.msg(); + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + @Override + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessMsgEnum.java b/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessMsgEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..8af171a41a68869e52c53eb9d33a9a0cac5f4bd5 --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/exception/BusinessMsgEnum.java @@ -0,0 +1,51 @@ +/* + * + * Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved. + * + * FileName:MsgEnum.java + * + * Description: + * + * History: + * Version Author Date Operation + * 1.0 lli 2017年8月3日下午2:02:18 Create + */ +package com.itcodai.course08.exception; + +/** + * 业务异常提示信息枚举类 + * @author shengwu ni + */ +public enum BusinessMsgEnum { + /** 参数异常 */ + PARMETER_EXCEPTION("102", "参数异常!"), + /** 等待超时 */ + SERVICE_TIME_OUT("103", "服务调用超时!"), + /** 参数过大 */ + PARMETER_BIG_EXCEPTION("102", "输入的图片数量不能超过50张!"), + /** 500 : 发生异常 */ + UNEXPECTED_EXCEPTION("500", "系统发生异常,请联系管理员!"); + + /** + * 消息码 + */ + private String code; + /** + * 消息内容 + */ + private String msg; + + private BusinessMsgEnum(String code, String msg) { + this.code = code; + this.msg = msg; + } + + public String code() { + return code; + } + + public String msg() { + return msg; + } + +} diff --git a/springboot-exception/src/main/java/com/itcodai/course08/exception/GlobalExceptionHandler.java b/springboot-exception/src/main/java/com/itcodai/course08/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..9191a16e581ff44444840d4c56cd7011ac679fd3 --- /dev/null +++ b/springboot-exception/src/main/java/com/itcodai/course08/exception/GlobalExceptionHandler.java @@ -0,0 +1,69 @@ +package com.itcodai.course08.exception; + +import com.itcodai.course08.entity.JsonResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ControllerAdvice +@ResponseBody +public class GlobalExceptionHandler { + + private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 拦截业务异常,返回业务异常信息 + * @param ex + * @return + */ + @ExceptionHandler(BusinessErrorException.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleBusinessError(BusinessErrorException ex) { + String code = ex.getCode(); + String message = ex.getMessage(); + return new JsonResult(code, message); + } + + /** + * 空指针异常 + * @param ex NullPointerException + * @return + */ + @ExceptionHandler(NullPointerException.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleTypeMismatchException(NullPointerException ex) { + logger.error("空指针异常,{}", ex.getMessage()); + return new JsonResult("500", "空指针异常了"); + } + + /** + * 缺少请求参数异常 + * @param ex HttpMessageNotReadableException + * @return + */ + @ExceptionHandler(MissingServletRequestParameterException.class) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public JsonResult handleHttpMessageNotReadableException( + MissingServletRequestParameterException ex) { + logger.error("缺少请求参数,{}", ex.getMessage()); + return new JsonResult("400", "缺少必要的请求参数"); + } + + /** + * 系统异常 预期以外异常 + * @param ex + * @return + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleUnexpectedServer(Exception ex) { + logger.error("系统异常:", ex); + return new JsonResult("500", "系统发生异常,请联系管理员"); + } + +} diff --git a/springboot-exception/src/main/resources/application.properties b/springboot-exception/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..1463f2b60f7a40359e4c76d61c2ab9b5336506d3 --- /dev/null +++ b/springboot-exception/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8089 \ No newline at end of file diff --git a/springboot-exception/src/test/java/com/itcodai/course08/Course08ApplicationTests.java b/springboot-exception/src/test/java/com/itcodai/course08/Course08ApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..e01a3d85b6c0f591205d790c0c5fc9e20871b216 --- /dev/null +++ b/springboot-exception/src/test/java/com/itcodai/course08/Course08ApplicationTests.java @@ -0,0 +1,16 @@ +package com.itcodai.course08; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Course08ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/springboot-filterchain/.gitignore b/springboot-filterchain/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..549e00a2a96fa9d7c5dbc9859664a78d980158c2 --- /dev/null +++ b/springboot-filterchain/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/springboot-filterchain/README.MD b/springboot-filterchain/README.MD new file mode 100644 index 0000000000000000000000000000000000000000..60eaee283192634dc6499d8e259d235c70444312 --- /dev/null +++ b/springboot-filterchain/README.MD @@ -0,0 +1,3 @@ +## 在springboot中实现过滤器链 + 在包filter中定义自己的过滤器,实现接口Filter。 + 在包config中增加配置类FilterConfig,分别注册自定义的过滤器。 diff --git a/springboot-filterchain/pom.xml b/springboot-filterchain/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..be6302734f7709d16484b2e7ca739e462040b186 --- /dev/null +++ b/springboot-filterchain/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + com.jxy + spingboot-filterchain + 0.0.1-SNAPSHOT + spingboot-filterchain + spingboot-filterchain + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.jxy.spingbootfilterchain.SpingbootFilterchainApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplication.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..6a30637e269774ff3deb92a302c1a17547651652 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplication.java @@ -0,0 +1,13 @@ +package com.jxy.spingbootfilterchain; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpingbootFilterchainApplication { + + public static void main(String[] args) { + SpringApplication.run(SpingbootFilterchainApplication.class, args); + } + +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/config/FilterConfig.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/config/FilterConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..fa2dd54c0c49245660ba97841b96e75cfa13dba9 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/config/FilterConfig.java @@ -0,0 +1,29 @@ +package com.jxy.spingbootfilterchain.config; + +import com.jxy.spingbootfilterchain.filter.FirstFilter; +import com.jxy.spingbootfilterchain.filter.SecondFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean firstFilter(){ + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new FirstFilter()); + registrationBean.addUrlPatterns("/*"); + registrationBean.setOrder(1); + return registrationBean; + } + + @Bean + public FilterRegistrationBean secondFilter(){ + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new SecondFilter()); + registrationBean.addUrlPatterns("/*"); + registrationBean.setOrder(2); //setOrder方法定义了过滤器的执行顺序,数字越小,优先级越高。 + return registrationBean; + } +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/BasicController.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/BasicController.java new file mode 100644 index 0000000000000000000000000000000000000000..e59a89896a009e0c8fec257e5f141a14a387fe7a --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/BasicController.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.spingbootfilterchain.demos.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author theonefx + */ +@Controller +public class BasicController { + + // http://127.0.0.1:8080/hello?name=lisi + @RequestMapping("/hello") + @ResponseBody + public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) { + return "Hello " + name; + } + + // http://127.0.0.1:8080/user + @RequestMapping("/user") + @ResponseBody + public User user() { + User user = new User(); + user.setName("theonefx"); + user.setAge(666); + return user; + } + + // http://127.0.0.1:8080/save_user?name=newName&age=11 + @RequestMapping("/save_user") + @ResponseBody + public String saveUser(User u) { + return "user will save: name=" + u.getName() + ", age=" + u.getAge(); + } + + // http://127.0.0.1:8080/html + @RequestMapping("/html") + public String html() { + return "index.html"; + } + + @ModelAttribute + public void parseUser(@RequestParam(name = "name", defaultValue = "unknown user") String name + , @RequestParam(name = "age", defaultValue = "12") Integer age, User user) { + user.setName("zhangsan"); + user.setAge(18); + } +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/PathVariableController.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/PathVariableController.java new file mode 100644 index 0000000000000000000000000000000000000000..a0ecd635e4dabb5efaad5e67d87955d743ec3b81 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/PathVariableController.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.spingbootfilterchain.demos.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author theonefx + */ +@Controller +public class PathVariableController { + + // http://127.0.0.1:8080/user/123/roles/222 + @RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET) + @ResponseBody + public String getLogin(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) { + return "User Id : " + userId + " Role Id : " + roleId; + } + + // http://127.0.0.1:8080/javabeat/somewords + @RequestMapping(value = "/javabeat/{regexp1:[a-z-]+}", method = RequestMethod.GET) + @ResponseBody + public String getRegExp(@PathVariable("regexp1") String regexp1) { + return "URI Part : " + regexp1; + } +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/User.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/User.java new file mode 100644 index 0000000000000000000000000000000000000000..086ae9a01f5d5d95e5f3e5c55ea3360fb1fbf444 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/demos/web/User.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.spingbootfilterchain.demos.web; + +/** + * @author theonefx + */ +public class User { + + private String name; + + private Integer age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/FirstFilter.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/FirstFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..78d403fa7a38ff7b92bdd706a6bc2e9a22728ad2 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/FirstFilter.java @@ -0,0 +1,30 @@ +package com.jxy.spingbootfilterchain.filter; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +public class FirstFilter implements Filter { + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + System.out.println("FirstFilter: URL="+httpServletRequest.getRequestURL()); + // 在调用下一个过滤器之前可以进行一些处理 + System.out.println("过滤器1,下一个过滤器前"); + // 如果有下一个过滤器,则调用 filterChain.doFilter(servletRequest,servletResponse) + filterChain.doFilter(servletRequest,servletResponse); + // 在调用下一个过滤器之后可以进行一些处理 + System.out.println("过滤器1,下一个过滤器后"); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + System.out.println("FirstFilter初始化"); + } + + @Override + public void destroy() { + System.out.println("FirstFilter销毁"); + } +} diff --git a/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/SecondFilter.java b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/SecondFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..3649a3197ed7ca568c80d8677371952acfa980e1 --- /dev/null +++ b/springboot-filterchain/src/main/java/com/jxy/spingbootfilterchain/filter/SecondFilter.java @@ -0,0 +1,24 @@ +package com.jxy.spingbootfilterchain.filter; + +import javax.servlet.*; +import java.io.IOException; + +public class SecondFilter implements Filter { + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + System.out.println("过滤器2"); + //自定义的最后一个拦截器必须要往下调用,不然mvc框架的过滤器就不起作用了 + filterChain.doFilter(servletRequest,servletResponse); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + System.out.println("SecondFilter初始化"); + } + + @Override + public void destroy() { + System.out.println("SecondFilter销毁"); + } +} diff --git a/springboot-filterchain/src/main/resources/application.properties b/springboot-filterchain/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..e52b49860b402d53164a87bfe88a26a1fa665f2c --- /dev/null +++ b/springboot-filterchain/src/main/resources/application.properties @@ -0,0 +1,3 @@ +# 应用服务 WEB 访问端口 +server.port=8080 + diff --git a/springboot-filterchain/src/main/resources/static/index.html b/springboot-filterchain/src/main/resources/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..89bb8ba4ff248cd6e3b8b5e2f89af4e3062a37a8 --- /dev/null +++ b/springboot-filterchain/src/main/resources/static/index.html @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + \ No newline at end of file diff --git a/springboot-filterchain/src/test/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplicationTests.java b/springboot-filterchain/src/test/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..fca1cc4622bf70ee5ced46971807422636442d64 --- /dev/null +++ b/springboot-filterchain/src/test/java/com/jxy/spingbootfilterchain/SpingbootFilterchainApplicationTests.java @@ -0,0 +1,13 @@ +package com.jxy.spingbootfilterchain; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpingbootFilterchainApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-listener/.gitignore b/springboot-listener/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..549e00a2a96fa9d7c5dbc9859664a78d980158c2 --- /dev/null +++ b/springboot-listener/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/springboot-listener/README.MD b/springboot-listener/README.MD new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/springboot-listener/pom.xml b/springboot-listener/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..df65abbc929149ccf6a1b8701537ca8f070cee3d --- /dev/null +++ b/springboot-listener/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + com.jxy + springboot-listener + 0.0.1-SNAPSHOT + springboot-listener + springboot-listener + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + UTF-8 + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.jxy.springbootlistener.SpringbootListenerApplication + true + + + + repackage + + repackage + + + + + + + + diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/SpringbootListenerApplication.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/SpringbootListenerApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..8a6844cff7628fc246cc4736543c97aca898f150 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/SpringbootListenerApplication.java @@ -0,0 +1,13 @@ +package com.jxy.springbootlistener; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringbootListenerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringbootListenerApplication.class, args); + } + +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/BasicController.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/BasicController.java new file mode 100644 index 0000000000000000000000000000000000000000..10a6bae72116740c7abdfc76039a625f44c65e5d --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/BasicController.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.springbootlistener.demos.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author theonefx + */ +@Controller +public class BasicController { + + // http://127.0.0.1:8080/hello?name=lisi + @RequestMapping("/hello") + @ResponseBody + public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) { + return "Hello " + name; + } + + // http://127.0.0.1:8080/user + @RequestMapping("/user") + @ResponseBody + public User user() { + User user = new User(); + user.setName("theonefx"); + user.setAge(666); + return user; + } + + // http://127.0.0.1:8080/save_user?name=newName&age=11 + @RequestMapping("/save_user") + @ResponseBody + public String saveUser(User u) { + return "user will save: name=" + u.getName() + ", age=" + u.getAge(); + } + + // http://127.0.0.1:8080/html + @RequestMapping("/html") + public String html() { + return "index.html"; + } + + @ModelAttribute + public void parseUser(@RequestParam(name = "name", defaultValue = "unknown user") String name + , @RequestParam(name = "age", defaultValue = "12") Integer age, User user) { + user.setName("zhangsan"); + user.setAge(18); + } +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/LoginController.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/LoginController.java new file mode 100644 index 0000000000000000000000000000000000000000..5a84c6b263a0a16e665a5c5dc7e3fac4eba5d852 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/LoginController.java @@ -0,0 +1,29 @@ +package com.jxy.springbootlistener.demos.web; + +import com.jxy.springbootlistener.eventPublish.MySessionEventPubLisher; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.annotation.Resource; +import javax.servlet.http.HttpSession; + +@Controller +public class LoginController { + + @Resource + private MySessionEventPubLisher mySessionEventPubLisher; + + @RequestMapping("login") + @ResponseBody + public String login(@RequestParam("name") String name,@RequestParam("pwd") String pwd, + HttpSession session){ + if ("admin".equals(name) && "123456".equals(pwd)){ + mySessionEventPubLisher.publishListener(session); + String msg = "登录成功,当前在线人数为:"+session.getServletContext().getAttribute("ONLINE_NUM"); + return msg; + } + return "验证信息不正确!"; + } +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/PathVariableController.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/PathVariableController.java new file mode 100644 index 0000000000000000000000000000000000000000..661e04e85b5ca528481ffe4f1c7ab4de572ea781 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/PathVariableController.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.springbootlistener.demos.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author theonefx + */ +@Controller +public class PathVariableController { + + // http://127.0.0.1:8080/user/123/roles/222 + @RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET) + @ResponseBody + public String getLogin(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) { + return "User Id : " + userId + " Role Id : " + roleId; + } + + // http://127.0.0.1:8080/javabeat/somewords + @RequestMapping(value = "/javabeat/{regexp1:[a-z-]+}", method = RequestMethod.GET) + @ResponseBody + public String getRegExp(@PathVariable("regexp1") String regexp1) { + return "URI Part : " + regexp1; + } +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/User.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/User.java new file mode 100644 index 0000000000000000000000000000000000000000..d1991427bf11858bc0836173dbdc9650c8ad98d2 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/demos/web/User.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.jxy.springbootlistener.demos.web; + +/** + * @author theonefx + */ +public class User { + + private String name; + + private Integer age; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/eventPublish/MySessionEventPubLisher.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/eventPublish/MySessionEventPubLisher.java new file mode 100644 index 0000000000000000000000000000000000000000..d744efe31b75e18758639ead7da65835d06a5928 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/eventPublish/MySessionEventPubLisher.java @@ -0,0 +1,20 @@ +package com.jxy.springbootlistener.eventPublish; + +import com.jxy.springbootlistener.events.SessionEvent; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpSession; + +@Component +public class MySessionEventPubLisher { + + @Autowired + private ApplicationEventPublisher applicationEventPublisher; + + public void publishListener(HttpSession session){ + applicationEventPublisher.publishEvent(new SessionEvent(this,session)); + } + +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/events/SessionEvent.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/events/SessionEvent.java new file mode 100644 index 0000000000000000000000000000000000000000..662324bd23bd215dadcc7590c3c7d5bf9e417236 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/events/SessionEvent.java @@ -0,0 +1,28 @@ +package com.jxy.springbootlistener.events; + +import org.springframework.context.ApplicationEvent; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; + +public class SessionEvent extends ApplicationEvent { + + private HttpSession session; + + public SessionEvent(Object source,HttpSession session){ + super(source); + this.session = session; + } + + public Integer getCount(){ + ServletContext servletContext = session.getServletContext(); + Integer online_num = (Integer)servletContext.getAttribute("ONLINE_NUM"); + if (null == online_num){ + online_num = 0; + } + online_num++; + servletContext.setAttribute("ONLINE_NUM",online_num); + System.out.println("新增一位在线用户!"); + return online_num; + } +} diff --git a/springboot-listener/src/main/java/com/jxy/springbootlistener/listener/MySessionListener.java b/springboot-listener/src/main/java/com/jxy/springbootlistener/listener/MySessionListener.java new file mode 100644 index 0000000000000000000000000000000000000000..06ebe58519ca9ef597ea63ad28a14f6403039804 --- /dev/null +++ b/springboot-listener/src/main/java/com/jxy/springbootlistener/listener/MySessionListener.java @@ -0,0 +1,15 @@ +package com.jxy.springbootlistener.listener; + +import com.jxy.springbootlistener.events.SessionEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +@Component +public class MySessionListener implements ApplicationListener { + + @Override + public void onApplicationEvent(SessionEvent event) { + Integer count = event.getCount(); + System.out.println("在线用户数为:"+count); + } +} diff --git a/springboot-listener/src/main/resources/application.properties b/springboot-listener/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..cf50fdc57d47214bb0a494797a5e86f92453fed1 --- /dev/null +++ b/springboot-listener/src/main/resources/application.properties @@ -0,0 +1,24 @@ +# THYMELEAF (ThymeleafAutoConfiguration) +# 开启模板缓存(默认值: true ) +spring.thymeleaf.cache=true +# 检查模板是否存在,然后再呈现 +spring.thymeleaf.check-template=true +# 检查模板位置是否正确(默认值 :true ) +spring.thymeleaf.check-template-location=true +#Content-Type 的值(默认值: text/html ) +spring.thymeleaf.content-type=text/html +# 开启 MVC Thymeleaf 视图解析(默认值: true ) +spring.thymeleaf.enabled=true +# 模板编码 +spring.thymeleaf.encoding=UTF-8 +# 要被排除在解析之外的视图名称列表,⽤逗号分隔 +spring.thymeleaf.excluded-view-names= +# 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5) +spring.thymeleaf.mode=HTML5 +# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ ) +spring.thymeleaf.prefix=classpath:/templates/ +# 在构建 URL 时添加到视图名称后的后缀(默认值: .html ) +spring.thymeleaf.suffix=.html +# 应用服务 WEB 访问端口 +server.port=8080 + diff --git a/springboot-listener/src/main/resources/static/index.html b/springboot-listener/src/main/resources/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..89bb8ba4ff248cd6e3b8b5e2f89af4e3062a37a8 --- /dev/null +++ b/springboot-listener/src/main/resources/static/index.html @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + \ No newline at end of file diff --git a/springboot-listener/src/test/java/com/jxy/springbootlistener/SpringbootListenerApplicationTests.java b/springboot-listener/src/test/java/com/jxy/springbootlistener/SpringbootListenerApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..77083e503cb68ff53832f7fe322fa1dd83b6a2f1 --- /dev/null +++ b/springboot-listener/src/test/java/com/jxy/springbootlistener/SpringbootListenerApplicationTests.java @@ -0,0 +1,13 @@ +package com.jxy.springbootlistener; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringbootListenerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/springboot-redis/pom.xml b/springboot-redis/pom.xml index daca3fdede787fb03fdad65c54089997b2a9363f..b214cd52fe7507b11d35c198e7fc1cd722365edd 100644 --- a/springboot-redis/pom.xml +++ b/springboot-redis/pom.xml @@ -30,6 +30,10 @@ + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-data-redis diff --git a/springboot-redis/src/main/java/com/xncoding/pos/controller/UserController.java b/springboot-redis/src/main/java/com/xncoding/pos/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..769b49b51ea4743b078a6e1e9969970e8a5c2b30 --- /dev/null +++ b/springboot-redis/src/main/java/com/xncoding/pos/controller/UserController.java @@ -0,0 +1,59 @@ +package com.xncoding.pos.controller; + +import com.xncoding.pos.dao.entity.User; +import com.xncoding.pos.service.UserService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +@RestController +public class UserController { + + @Resource + private UserService userService; + + @PostMapping("/saveUser") + public String saveUser(@RequestBody User user){ + String msg = ""; + if (user != null){ + userService.createUser(user); + msg = "用户保存成功,用户为"+user.getUsername(); + } + return msg; + } + + @GetMapping("/") + public String indexPage(){ + return "系统首页"; + } + + @GetMapping("/getUser/{id}") + public String getUser(@PathVariable("id")Integer id){ + User user = new User(); + if (id != null){ + user = userService.getById(id); + } + return user.toString(); + } + + @PostMapping("updateUser") + public String updateUser(@RequestBody User user){ + String msg = ""; + if (user != null){ + userService.updateUser(user); + msg = "用户更新成功,更新后的用户名为:"+user.getUsername(); + } + return msg; + } + + @DeleteMapping("delUser/{id}") + public String delUser(@PathVariable("id")Integer id){ + String msg = ""; + if (id != null){ + User user = userService.getById(id); + userService.deleteById(id); + msg = "用户"+user.getUsername()+"删除成功!"; + } + return msg; + } +} diff --git a/springboot-redis/src/main/java/com/xncoding/pos/service/UserService.java b/springboot-redis/src/main/java/com/xncoding/pos/service/UserService.java index 9fd3baf426b2a48350562d5a13210dc57e634689..9618f7ad9f51a011a9be5c9c8aaffaf32e1733c1 100644 --- a/springboot-redis/src/main/java/com/xncoding/pos/service/UserService.java +++ b/springboot-redis/src/main/java/com/xncoding/pos/service/UserService.java @@ -57,7 +57,7 @@ public class UserService { // 缓存不存在,从 DB 中获取 User user = userMapper.selectById(id); // 插入缓存 - operations.set(key, user, 10, TimeUnit.SECONDS); + operations.set(key, user, 1000, TimeUnit.SECONDS); return user; } @@ -79,6 +79,11 @@ public class UserService { if (hasKey) { redisTemplate.delete(key); logger.info("更新用户时候,从缓存中删除用户 >> " + userId); + }else { + User user1 = userMapper.selectById(user.getId()); + ValueOperations operations = redisTemplate.opsForValue(); + // 插入缓存 + operations.set(key, user1, 1000, TimeUnit.SECONDS); } } diff --git a/springboot-redis/src/main/resources/application.yml b/springboot-redis/src/main/resources/application.yml index 18f437dede72d92aedd4eee8c8b8243942d278fb..f51681d448c20e33fd3abe3645ac6096460ba0f7 100644 --- a/springboot-redis/src/main/resources/application.yml +++ b/springboot-redis/src/main/resources/application.yml @@ -7,9 +7,9 @@ spring: profiles: active: dev datasource: - url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 + url: jdbc:mysql://127.0.0.1:3306/redis-test?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 username: root - password: 123456 + password: root ################### mybatis-plus配置 ################### mybatis-plus: @@ -56,3 +56,6 @@ logging: xncoding: DEBUG file: D:/logs/app.log +server: + port: 8089 + diff --git a/springboot-shiro/pom.xml b/springboot-shiro/pom.xml index d0311ec2e8b3aef8ff5a12f1db582ad84261465f..88df6bf075a1fc2fd478b0dff39a5dd10be36af9 100644 --- a/springboot-shiro/pom.xml +++ b/springboot-shiro/pom.xml @@ -23,7 +23,7 @@ UTF-8 1.8 1.1.2 - 8.0.7-dmr + 5.1.46 2.1.8 1.0.5 diff --git a/springboot-shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java b/springboot-shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java index 7cb442496d4438b7178224d1ce53558bc53dc0da..2afac3e7cca1f7357980dd59c2e610792e04e5ea 100644 --- a/springboot-shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java +++ b/springboot-shiro/src/main/java/com/xncoding/pos/config/properties/DruidProperties.java @@ -24,7 +24,7 @@ public class DruidProperties { private String password; - private String driverClassName = "com.mysql.cj.jdbc.Driver"; + private String driverClassName = "com.mysql.jdbc.Driver"; private Integer initialSize = 10; diff --git a/springboot-shiro/src/main/resources/application.yml b/springboot-shiro/src/main/resources/application.yml index 0627a472743e8d99f11f8f058646ccdb6967862a..29d157f3134698981ceb7211c1f92617daf48675 100644 --- a/springboot-shiro/src/main/resources/application.yml +++ b/springboot-shiro/src/main/resources/application.yml @@ -55,7 +55,7 @@ spring: datasource: url: jdbc:mysql://127.0.0.1:3306/pos?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 username: root - password: 123456 + password: root thymeleaf: cache: false diff --git a/springboot-shironew/.gitignore b/springboot-shironew/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..82eca336e352c9026decda294ff678968050edfc --- /dev/null +++ b/springboot-shironew/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/springboot-shironew/.mvn/wrapper/maven-wrapper.jar b/springboot-shironew/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9cc84ea9b4d95453115d0c26488d6a78694e0bc6 Binary files /dev/null and b/springboot-shironew/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-shironew/.mvn/wrapper/maven-wrapper.properties b/springboot-shironew/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..b573bb50d56e8c19282593cbf5b081e211923a83 --- /dev/null +++ b/springboot-shironew/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/springboot-shironew/mvnw b/springboot-shironew/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..5bf251c0774593ca4f5335acf0f7483eaa162e8f --- /dev/null +++ b/springboot-shironew/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-shironew/mvnw.cmd b/springboot-shironew/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..019bd74d766ebd4c033528112148d866555b5c9e --- /dev/null +++ b/springboot-shironew/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-shironew/pom.xml b/springboot-shironew/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..c1f86c71b64996252ec9cdae2333fa98c0474e70 --- /dev/null +++ b/springboot-shironew/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + com.itcodai + course16 + 0.0.1-SNAPSHOT + jar + + course16 + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.shiro + shiro-spring + 1.4.0 + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.2 + + + mysql + mysql-connector-java + runtime + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/Course16Application.java b/springboot-shironew/src/main/java/com/itcodai/course16/Course16Application.java new file mode 100644 index 0000000000000000000000000000000000000000..e04b0336991aac91b72291e6b5ce0381af188c72 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/Course16Application.java @@ -0,0 +1,14 @@ +package com.itcodai.course16; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan("com.itcodai.course16.dao") +public class Course16Application { + + public static void main(String[] args) { + SpringApplication.run(Course16Application.class, args); + } +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/config/ShiroConfig.java b/springboot-shironew/src/main/java/com/itcodai/course16/config/ShiroConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..05ba0f90497185f9e4087e2ca91cb1d27a82175b --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/config/ShiroConfig.java @@ -0,0 +1,101 @@ +package com.itcodai.course16.config; + +import com.itcodai.course16.realm.MyRealm; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Shiro配置类 + * @author shengwu ni + * @date 2018/08/20 + */ +@Configuration +public class ShiroConfig { + + private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class); + + /** + * 注入自定义的realm + * @return MyRealm + */ + @Bean + public MyRealm myAuthRealm() { + MyRealm myRealm = new MyRealm(); + logger.info("====myRealm注册完成====="); + return myRealm; + } + + /** + * 注入安全管理器 + * @return SecurityManager + */ + @Bean + public SecurityManager securityManager() { + // 将自定义realm加进来 + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(myAuthRealm()); + logger.info("====securityManager注册完成===="); + return securityManager; + } + + /** + * 注入Shiro过滤器 + * @param securityManager 配置安全管理器 + * @return ShiroFilterFactoryBean + */ + @Bean + public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { + // 定义shiroFactoryBean + ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean(); + + // 设置自定义的securityManager + shiroFilterFactoryBean.setSecurityManager(securityManager); + + // 设置默认登录的url,身份认证失败会访问该url + shiroFilterFactoryBean.setLoginUrl("/login"); + // 设置成功之后要跳转的链接 + shiroFilterFactoryBean.setSuccessUrl("/success"); + // 设置未授权界面,权限认证失败会访问该url + shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized"); + + // LinkedHashMap是有序的,进行顺序拦截器配置 + Map filterChainMap = new LinkedHashMap<>(); + + // 配置可以匿名访问的地址,可以根据实际情况自己添加,放行一些静态资源等 + filterChainMap.put("/css/**", "anon"); + filterChainMap.put("/imgs/**", "anon"); + filterChainMap.put("/js/**", "anon"); + filterChainMap.put("/swagger-*/**", "anon"); + filterChainMap.put("/swagger-ui.html/**", "anon"); + // 登录url 放行 + filterChainMap.put("/login", "anon"); + + // “/user/admin” 开头的需要身份认证 + filterChainMap.put("/user/admin*", "authc"); + // “/user/student” 开头的需要角色认证,是“admin”才允许 + filterChainMap.put("/user/student*/**", "roles[admin]"); + // “/user/teacher” 开头的需要权限认证,是“user:create”才允许 + filterChainMap.put("/user/teacher*/**", "perms[\"user:create\"]"); +// filterChainMap.put("/user/test*/**", "perms[\"student:create\"]"); + + // 配置logout过滤器 + filterChainMap.put("/logout", "logout"); + // 所有url必须通过认证才可以访问,这行代码必须放在所有权限设置的最后 +// filterChainMap.put("/**", "authc"); + + + // 设置shiroFilterFactoryBean的FilterChainDefinitionMap + shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap); + logger.info("====shiroFilterFactoryBean注册完成===="); + return shiroFilterFactoryBean; + } + + +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/controller/IndexController.java b/springboot-shironew/src/main/java/com/itcodai/course16/controller/IndexController.java new file mode 100644 index 0000000000000000000000000000000000000000..40110a87188785dc33db32b6205e42928410bd38 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/controller/IndexController.java @@ -0,0 +1,22 @@ +package com.itcodai.course16.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * 跳转Controller + * @author shengwu ni + */ +@Controller +public class IndexController { + + @GetMapping("/login") + public String login() { + return "login"; + } + + @GetMapping("/unauthorized") + public String unauthorized() { + return "unauthorized"; + } +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/controller/UserController.java b/springboot-shironew/src/main/java/com/itcodai/course16/controller/UserController.java new file mode 100644 index 0000000000000000000000000000000000000000..19fd12031299fb11f50bcc05a9c629d5bfe3ea76 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/controller/UserController.java @@ -0,0 +1,84 @@ +package com.itcodai.course16.controller; + +import com.itcodai.course16.entity.User; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +/** + * 用户Controller + * @author shengwu ni + */ +@Controller +@RequestMapping("/user") +public class UserController { + + /** + * 用户登录接口 + * @param user user + * @param request request + * @return string + */ + @PostMapping("/login") + public String login(User user, HttpServletRequest request) { + + // 根据用户名和密码创建token + UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); + // 获取subject认证主体 + Subject subject = SecurityUtils.getSubject(); + try{ + // 开始认证,这一步会跳到我们自定义的realm中 + subject.login(token); + request.getSession().setAttribute("user", user); + return "success"; + }catch(Exception e){ + e.printStackTrace(); + request.getSession().setAttribute("user", user); + request.setAttribute("error", "用户名或密码错误!"); + return "login"; + } + } + + @RequestMapping("/logout") + public String logout() { + SecurityUtils.getSubject().logout(); + return "login"; + } + + /** + * 身份认证测试接口 + * @param request + * @return + */ + @RequestMapping("/admin") + public String admin(HttpServletRequest request) { + Object user = request.getSession().getAttribute("user"); + return "success"; + } + + /** + * 角色认证测试接口 + * @param request + * @return + */ + @RequestMapping("/student") + public String student(HttpServletRequest request) { + return "success"; + } + + /** + * 权限认证测试接口 + * @param request + * @return + */ + @RequestMapping("/teacher") + public String teacher(HttpServletRequest request) { + return "success"; + } +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/dao/UserDao.java b/springboot-shironew/src/main/java/com/itcodai/course16/dao/UserDao.java new file mode 100644 index 0000000000000000000000000000000000000000..6d4130ef9c448c4f2d77e1439bbdefa058cc1751 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/dao/UserDao.java @@ -0,0 +1,21 @@ +package com.itcodai.course16.dao; + +import com.itcodai.course16.entity.User; +import org.apache.ibatis.annotations.Select; + +import java.util.Set; + +public interface UserDao { + + @Select("select * from t_user where username = #{username}") + User getByUsername(String username); + + @Select("select r.rolename from t_user u,t_role r " + + "where u.role_id = r.id and u.username = #{username}") + Set getRoles(String username); + + @Select("select p.permissionname from t_user u,t_role r,t_permission p " + + "where u.role_id = r.id and p.role_id = r.id and u.username = #{username}") + Set getPermissions(String username); + +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/entity/JsonResult.java b/springboot-shironew/src/main/java/com/itcodai/course16/entity/JsonResult.java new file mode 100644 index 0000000000000000000000000000000000000000..31090b3ffa3c5412c06d348320c91dc32b1a7ef0 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/entity/JsonResult.java @@ -0,0 +1,54 @@ +package com.itcodai.course16.entity; + +/** + * 统一返回的异常封装实体 + */ +public class JsonResult { + + /** + * 异常码 + */ + protected String code; + + /** + * 异常信息 + */ + protected String msg; + + public JsonResult() { + this.code = "200"; + this.msg = "操作成功"; + } + + public JsonResult(String code, String msg) { + this.code = code; + this.msg = msg; + } + +// public JsonResult(BusinessErrorException ex) { +// this.code = ex.getCode(); +// this.msg = ex.getMessage(); +// } +// +// public JsonResult(BusinessMsgEnum msg) { +// this.code = msg.code(); +// this.msg = msg.msg(); +// } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/entity/User.java b/springboot-shironew/src/main/java/com/itcodai/course16/entity/User.java new file mode 100644 index 0000000000000000000000000000000000000000..adf48bd807d6fa03f8daae057e4ec4d5ea13c702 --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/entity/User.java @@ -0,0 +1,32 @@ +package com.itcodai.course16.entity; + +public class User { + + private Integer id; + private String username; + private String password; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/realm/MyRealm.java b/springboot-shironew/src/main/java/com/itcodai/course16/realm/MyRealm.java new file mode 100644 index 0000000000000000000000000000000000000000..f5135e1bd771e9564bee7ca87123dc622a987dba --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/realm/MyRealm.java @@ -0,0 +1,55 @@ +package com.itcodai.course16.realm; + +import com.itcodai.course16.entity.User; +import com.itcodai.course16.service.UserService; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; + +import javax.annotation.Resource; + +/** + * 自定义realm + * @author shengwu ni + */ +public class MyRealm extends AuthorizingRealm { + + @Resource + private UserService userService; + + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { + // 获取用户名 + String username = (String) principalCollection.getPrimaryPrincipal(); + SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); + // 给该用户设置角色,角色信息存在t_role表中取 + authorizationInfo.setRoles(userService.getRoles(username)); + // 给该用户设置权限,权限信息存在t_permission表中取 + authorizationInfo.setStringPermissions(userService.getPermissions(username)); + return authorizationInfo; + } + + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { + // 根据token获取用户名 + String username = (String) authenticationToken.getPrincipal(); + // 根据用户名从数据库中查询该用户 + User user = userService.getByUsername(username); + if(user != null) { + // 把当前用户存到session中 + SecurityUtils.getSubject().getSession().setAttribute("user", user); + // 传入用户名和密码进行身份认证,并返回认证信息 + AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), "myRealm"); + return authcInfo; + } else { + return null; + } + } +} + diff --git a/springboot-shironew/src/main/java/com/itcodai/course16/service/UserService.java b/springboot-shironew/src/main/java/com/itcodai/course16/service/UserService.java new file mode 100644 index 0000000000000000000000000000000000000000..7d7ad3aaff1594c6776982f4324e2fb96920519c --- /dev/null +++ b/springboot-shironew/src/main/java/com/itcodai/course16/service/UserService.java @@ -0,0 +1,28 @@ +package com.itcodai.course16.service; + +import com.itcodai.course16.dao.UserDao; +import com.itcodai.course16.entity.User; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Set; + +@Service +public class UserService { + + @Resource + private UserDao userDao; + + + public User getByUsername(String username) { + return userDao.getByUsername(username); + } + + public Set getRoles(String username) { + return userDao.getRoles(username); + } + + public Set getPermissions(String username) { + return userDao.getPermissions(username); + } +} diff --git a/springboot-shironew/src/main/resources/application.yml b/springboot-shironew/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..8c0c78ccd4e6e6bcf12dfde99b68544892fb837a --- /dev/null +++ b/springboot-shironew/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 8080 + +# 数据库地址 +datasource: + url: localhost:3306/blog_test + +spring: + datasource: # 数据库配置 + driver-class-name: com.mysql.jdbc.Driver + url: jdbc:mysql://${datasource.url}?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 + username: root + password: 123456 + hikari: + maximum-pool-size: 10 # 最大连接池数 + max-lifetime: 1770000 + +mybatis: + # 指定别名设置的包为所有entity + type-aliases-package: com.itcodai.course16.entity + configuration: + map-underscore-to-camel-case: true # 驼峰命名规范 + mapper-locations: # mapper映射文件位置 + - classpath:mapper/*.xml \ No newline at end of file diff --git a/springboot-shironew/src/main/resources/templates/login.html b/springboot-shironew/src/main/resources/templates/login.html new file mode 100644 index 0000000000000000000000000000000000000000..ea3e26ccca3296c15ad08d2f818ca3cdcb9ac3a5 --- /dev/null +++ b/springboot-shironew/src/main/resources/templates/login.html @@ -0,0 +1,14 @@ + + + + + 登录页面 + + +
+ username:
+ password:
+ +
+ + \ No newline at end of file diff --git a/springboot-shironew/src/main/resources/templates/success.html b/springboot-shironew/src/main/resources/templates/success.html new file mode 100644 index 0000000000000000000000000000000000000000..ab239cb339ab39fe198608adc1f4d00dc351fe52 --- /dev/null +++ b/springboot-shironew/src/main/resources/templates/success.html @@ -0,0 +1,11 @@ + + + + + 成功 + + +欢迎你 +退出 + + \ No newline at end of file diff --git a/springboot-shironew/src/main/resources/templates/unauthorized.html b/springboot-shironew/src/main/resources/templates/unauthorized.html new file mode 100644 index 0000000000000000000000000000000000000000..b98fae55d9278e6b96b8f8a6ee373f497bbffbaa --- /dev/null +++ b/springboot-shironew/src/main/resources/templates/unauthorized.html @@ -0,0 +1,11 @@ + + + + + 认证未成功页面 + + +认证未通过,或者权限不足 +退出 + + \ No newline at end of file diff --git a/springboot-shironew/src/test/java/com/itcodai/course16/Course16ApplicationTests.java b/springboot-shironew/src/test/java/com/itcodai/course16/Course16ApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..de42bde1f4b54b31ce01bd107faf036b54a388e7 --- /dev/null +++ b/springboot-shironew/src/test/java/com/itcodai/course16/Course16ApplicationTests.java @@ -0,0 +1,16 @@ +package com.itcodai.course16; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Course16ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/springboot-sl4fj/.gitignore b/springboot-sl4fj/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..82eca336e352c9026decda294ff678968050edfc --- /dev/null +++ b/springboot-sl4fj/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/springboot-sl4fj/.mvn/wrapper/maven-wrapper.jar b/springboot-sl4fj/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..9cc84ea9b4d95453115d0c26488d6a78694e0bc6 Binary files /dev/null and b/springboot-sl4fj/.mvn/wrapper/maven-wrapper.jar differ diff --git a/springboot-sl4fj/.mvn/wrapper/maven-wrapper.properties b/springboot-sl4fj/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..b573bb50d56e8c19282593cbf5b081e211923a83 --- /dev/null +++ b/springboot-sl4fj/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/springboot-sl4fj/README.MD b/springboot-sl4fj/README.MD new file mode 100644 index 0000000000000000000000000000000000000000..a9d3cb09fe9be4441c55b9c87c60f54a8ce11493 --- /dev/null +++ b/springboot-sl4fj/README.MD @@ -0,0 +1 @@ +见pdf第三课 \ No newline at end of file diff --git a/springboot-sl4fj/logback.xml b/springboot-sl4fj/logback.xml new file mode 100644 index 0000000000000000000000000000000000000000..6283da41bf2ada04f81c15aa186bf88f739c06a5 --- /dev/null +++ b/springboot-sl4fj/logback.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + ${LOG_PATTERN} + + + + + + + ${FILE_PATH} + + 15 + + + 10MB + + + + + ${LOG_PATTERN} + + + + + + + + + + + \ No newline at end of file diff --git a/springboot-sl4fj/mvnw b/springboot-sl4fj/mvnw new file mode 100644 index 0000000000000000000000000000000000000000..5bf251c0774593ca4f5335acf0f7483eaa162e8f --- /dev/null +++ b/springboot-sl4fj/mvnw @@ -0,0 +1,225 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Migwn, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +echo $MAVEN_PROJECTBASEDIR +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/springboot-sl4fj/mvnw.cmd b/springboot-sl4fj/mvnw.cmd new file mode 100644 index 0000000000000000000000000000000000000000..019bd74d766ebd4c033528112148d866555b5c9e --- /dev/null +++ b/springboot-sl4fj/mvnw.cmd @@ -0,0 +1,143 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" + +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/springboot-sl4fj/pom.xml b/springboot-sl4fj/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..f3b75558f8b38642fa00dd7c3b050e5cec7a60ef --- /dev/null +++ b/springboot-sl4fj/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.itcodai + course03 + 0.0.1-SNAPSHOT + jar + + course03 + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/springboot-sl4fj/src/main/java/com/itcodai/course03/Course03Application.java b/springboot-sl4fj/src/main/java/com/itcodai/course03/Course03Application.java new file mode 100644 index 0000000000000000000000000000000000000000..ce9a97baaef818debfc7d01137729faafc166e52 --- /dev/null +++ b/springboot-sl4fj/src/main/java/com/itcodai/course03/Course03Application.java @@ -0,0 +1,12 @@ +package com.itcodai.course03; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Course03Application { + + public static void main(String[] args) { + SpringApplication.run(Course03Application.class, args); + } +} diff --git a/springboot-sl4fj/src/main/java/com/itcodai/course03/controller/TestController.java b/springboot-sl4fj/src/main/java/com/itcodai/course03/controller/TestController.java new file mode 100644 index 0000000000000000000000000000000000000000..4c168a04c1ff8b3149fdfa5edb08ecd1bc4967b1 --- /dev/null +++ b/springboot-sl4fj/src/main/java/com/itcodai/course03/controller/TestController.java @@ -0,0 +1,28 @@ +package com.itcodai.course03.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/test") +public class TestController { + + private final static Logger logger = LoggerFactory.getLogger(TestController.class); + + @RequestMapping("/log") + public String testLog() { + logger.debug("=====测试日志debug级别打印===="); + logger.info("======测试日志info级别打印====="); + logger.error("=====测试日志error级别打印===="); + logger.warn("======测试日志warn级别打印====="); + + // 可以使用占位符打印出一些参数信息 + String str1 = "blog.itcodai.com"; + String str2 = "blog.csdn.net/eson_15"; + logger.info("======倪升武的个人博客:{};倪升武的CSDN博客:{}", str1, str2); + + return "success"; + } +} diff --git a/springboot-sl4fj/src/main/java/com/itcodai/course03/dao/UserMapper.java b/springboot-sl4fj/src/main/java/com/itcodai/course03/dao/UserMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..6b2357e94cfcfe607258a1113fd8d48b8880eb8e --- /dev/null +++ b/springboot-sl4fj/src/main/java/com/itcodai/course03/dao/UserMapper.java @@ -0,0 +1,6 @@ +package com.itcodai.course03.dao; + +public interface UserMapper { + + void deleteUser(Long id); +} diff --git a/springboot-sl4fj/src/main/resources/application.yml b/springboot-sl4fj/src/main/resources/application.yml new file mode 100644 index 0000000000000000000000000000000000000000..f974e8c1ba1251ae9f1769a04e9caa3dedc9c054 --- /dev/null +++ b/springboot-sl4fj/src/main/resources/application.yml @@ -0,0 +1,4 @@ +logging: + config: springboot-sl4fj/logback.xml + level: + com.itcodai.course03.dao: trace diff --git a/springboot-sl4fj/src/test/java/com/itcodai/course03/Course03ApplicationTests.java b/springboot-sl4fj/src/test/java/com/itcodai/course03/Course03ApplicationTests.java new file mode 100644 index 0000000000000000000000000000000000000000..96de47461acc362adbb0e8ea2e693739d6df2c11 --- /dev/null +++ b/springboot-sl4fj/src/test/java/com/itcodai/course03/Course03ApplicationTests.java @@ -0,0 +1,16 @@ +package com.itcodai.course03; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Course03ApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/springboot-ssmconfig/pom.xml b/springboot-ssmconfig/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..81327920781587cbeec262463496028bfcc3208c --- /dev/null +++ b/springboot-ssmconfig/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + com.jxy + springboot-ssmconfig + 1.0-SNAPSHOT + + + + + org.springframework + spring-webmvc + 5.1.6.RELEASE + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + + + \ No newline at end of file diff --git a/springboot-ssmconfig/src/main/java/com/jxy/WebInit.java b/springboot-ssmconfig/src/main/java/com/jxy/WebInit.java new file mode 100644 index 0000000000000000000000000000000000000000..14dda7b5403244d59ef3c2f9aafe426c276066c7 --- /dev/null +++ b/springboot-ssmconfig/src/main/java/com/jxy/WebInit.java @@ -0,0 +1,34 @@ +package com.jxy; +import com.jxy.config.SpringMVCConfig; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +/** + * 这个类必须放在包的根目录下 + * 项目要启动,要在idea的项目结构中配置web,指向webapp + */ +public class WebInit implements WebApplicationInitializer { + + public void onStartup(ServletContext servletContext) throws ServletException { + //首先来加载 SpringMVC 的配置文件 + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(SpringMVCConfig.class); + // 添加 DispatcherServlet + ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx)); + // 给 DispatcherServlet 添加路径映射 + springmvc.addMapping("/"); + // 给 DispatcherServlet 添加启动时机 + springmvc.setLoadOnStartup(1); + } + + /** + * WebInit 的作用类似于 web.xml,这个类需要实现 WebApplicationInitializer 接口,并实现接口中的方法,当项目启动时, + * onStartup 方法会被自动执行,我们可以在这个方法中做一些项目初始化操作,例如加载 SpringMVC 容器,添加过滤器, + * 添加 Listener、添加 Servlet 等。 + */ +} \ No newline at end of file diff --git a/springboot-ssmconfig/src/main/java/com/jxy/config/SpringMVCConfig.java b/springboot-ssmconfig/src/main/java/com/jxy/config/SpringMVCConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..8fe6e44f745a8210be96a2eb9d00b984ae98e515 --- /dev/null +++ b/springboot-ssmconfig/src/main/java/com/jxy/config/SpringMVCConfig.java @@ -0,0 +1,9 @@ +package com.jxy.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.jxy") +public class SpringMVCConfig { +} diff --git a/springboot-ssmconfig/src/main/java/com/jxy/controller/HelloController.java b/springboot-ssmconfig/src/main/java/com/jxy/controller/HelloController.java new file mode 100644 index 0000000000000000000000000000000000000000..a27d72a4749841bfd0c80ea1c01f71067f52b82e --- /dev/null +++ b/springboot-ssmconfig/src/main/java/com/jxy/controller/HelloController.java @@ -0,0 +1,12 @@ +package com.jxy.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloController { + @GetMapping("/hello") + public String hello() { + return "hello"; + } +} diff --git a/springboot-starter-exception/pom.xml b/springboot-starter-exception/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..44a19dda879a280ef1eef38cd16973802cb63d58 --- /dev/null +++ b/springboot-starter-exception/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + + org.example + springboot-starter-exception + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-web + 2.0.3.RELEASE + + + \ No newline at end of file diff --git a/springboot-starter-exception/src/main/java/org/example/entity/Book.java b/springboot-starter-exception/src/main/java/org/example/entity/Book.java new file mode 100644 index 0000000000000000000000000000000000000000..9b02f42b298bb34733d19985f7c3010ac5973dc8 --- /dev/null +++ b/springboot-starter-exception/src/main/java/org/example/entity/Book.java @@ -0,0 +1,32 @@ +package org.example.entity; + +public class Book { + + private int id; + + private String name; + + public Book(int id, String name) { + this.id = id; + this.name = name; + } + + public Book() { + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/springboot-starter-exception/src/main/java/org/example/entity/JsonResult.java b/springboot-starter-exception/src/main/java/org/example/entity/JsonResult.java new file mode 100644 index 0000000000000000000000000000000000000000..f1257c60e28c62b5598f70dde93428cbe4dc0311 --- /dev/null +++ b/springboot-starter-exception/src/main/java/org/example/entity/JsonResult.java @@ -0,0 +1,54 @@ +package org.example.entity; + +/** + * 统一返回的异常封装实体 + */ +public class JsonResult { + + /** + * 异常码 + */ + protected String code; + + /** + * 异常信息 + */ + protected String msg; + + public JsonResult() { + this.code = "200"; + this.msg = "操作成功"; + } + + public JsonResult(String code, String msg) { + this.code = code; + this.msg = msg; + } + +// public JsonResult(BusinessErrorException ex) { +// this.code = ex.getCode(); +// this.msg = ex.getMessage(); +// } +// +// public JsonResult(BusinessMsgEnum msg) { +// this.code = msg.code(); +// this.msg = msg.msg(); +// } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/springboot-starter-exception/src/main/java/org/example/exception/BusinessErrorException.java b/springboot-starter-exception/src/main/java/org/example/exception/BusinessErrorException.java new file mode 100644 index 0000000000000000000000000000000000000000..5e33098b2a4edfa40fa8550cf9467c213cfdf957 --- /dev/null +++ b/springboot-starter-exception/src/main/java/org/example/exception/BusinessErrorException.java @@ -0,0 +1,54 @@ +/* + * + * Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved. + * + * FileName:BusinessErrorException.java + * + * Description: + * + * History: + * Version Author Date Operation + * 1.0 lli 2017年8月2日下午5:30:56 Create + */ +package org.example.exception; + +/** + * 自定义业务异常 + * @author shengwu ni + */ +public class BusinessErrorException extends RuntimeException { + + private static final long serialVersionUID = -7480022450501760611L; + + /** + * 异常码 + */ + private String code; + + /** + * 异常提示信息 + */ + private String message; + + public BusinessErrorException(BusinessMsgEnum businessMsgEnum) { + this.code = businessMsgEnum.code(); + this.message = businessMsgEnum.msg(); + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + @Override + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/springboot-starter-exception/src/main/java/org/example/exception/BusinessMsgEnum.java b/springboot-starter-exception/src/main/java/org/example/exception/BusinessMsgEnum.java new file mode 100644 index 0000000000000000000000000000000000000000..9de2bf3c58ef4e57576964396a3f528ba0d5d95f --- /dev/null +++ b/springboot-starter-exception/src/main/java/org/example/exception/BusinessMsgEnum.java @@ -0,0 +1,51 @@ +/* + * + * Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved. + * + * FileName:MsgEnum.java + * + * Description: + * + * History: + * Version Author Date Operation + * 1.0 lli 2017年8月3日下午2:02:18 Create + */ +package org.example.exception; + +/** + * 业务异常提示信息枚举类 + * @author shengwu ni + */ +public enum BusinessMsgEnum { + /** 参数异常 */ + PARMETER_EXCEPTION("102", "参数异常!"), + /** 等待超时 */ + SERVICE_TIME_OUT("103", "服务调用超时!"), + /** 参数过大 */ + PARMETER_BIG_EXCEPTION("102", "输入的图片数量不能超过50张!"), + /** 500 : 发生异常 */ + UNEXPECTED_EXCEPTION("500", "系统发生异常,请联系管理员!"); + + /** + * 消息码 + */ + private String code; + /** + * 消息内容 + */ + private String msg; + + private BusinessMsgEnum(String code, String msg) { + this.code = code; + this.msg = msg; + } + + public String code() { + return code; + } + + public String msg() { + return msg; + } + +} diff --git a/springboot-starter-exception/src/main/java/org/example/exception/GlobalExceptionHandler.java b/springboot-starter-exception/src/main/java/org/example/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..78ce93b02975d4184670ff08a1287be2b3137ad5 --- /dev/null +++ b/springboot-starter-exception/src/main/java/org/example/exception/GlobalExceptionHandler.java @@ -0,0 +1,69 @@ +package org.example.exception; + +import org.example.entity.JsonResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ControllerAdvice +@ResponseBody +public class GlobalExceptionHandler { + + private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 拦截业务异常,返回业务异常信息 + * @param ex + * @return + */ + @ExceptionHandler(BusinessErrorException.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleBusinessError(BusinessErrorException ex) { + String code = ex.getCode(); + String message = ex.getMessage(); + return new JsonResult(code, message); + } + + /** + * 空指针异常 + * @param ex NullPointerException + * @return + */ + @ExceptionHandler(NullPointerException.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleTypeMismatchException(NullPointerException ex) { + logger.error("空指针异常,{}", ex.getMessage()); + return new JsonResult("500", "空指针异常了"); + } + + /** + * 缺少请求参数异常 + * @param ex HttpMessageNotReadableException + * @return + */ + @ExceptionHandler(MissingServletRequestParameterException.class) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public JsonResult handleHttpMessageNotReadableException( + MissingServletRequestParameterException ex) { + logger.error("缺少请求参数,{}", ex.getMessage()); + return new JsonResult("400", "缺少必要的请求参数"); + } + + /** + * 系统异常 预期以外异常 + * @param ex + * @return + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + public JsonResult handleUnexpectedServer(Exception ex) { + logger.error("系统异常:", ex); + return new JsonResult("500", "系统发生异常,请联系管理员"); + } + +} diff --git a/springboot-starter-exception/src/main/resources/META-INF/spring.factories b/springboot-starter-exception/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000000000000000000000000000000000..c1b8ce234ee383d5d7cb056d7353c672001662d6 --- /dev/null +++ b/springboot-starter-exception/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.exception.GlobalExceptionHandler\ + ,org.example.entity.Book \ No newline at end of file diff --git a/springboot-starter1/pom.xml b/springboot-starter1/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..b3bf5a5b32267e107731b10fa5e7c2a481ffc9d1 --- /dev/null +++ b/springboot-starter1/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + com.jxy + springboot-starter1 + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-autoconfigure + 2.1.8.RELEASE + + + + org.springframework.boot + spring-boot-configuration-processor + 2.1.8.RELEASE + + + + + + \ No newline at end of file diff --git a/springboot-starter1/src/main/java/com/jxy/HelloProperties.java b/springboot-starter1/src/main/java/com/jxy/HelloProperties.java new file mode 100644 index 0000000000000000000000000000000000000000..8e82aaa899470264f5fd891961fc52a8e3330c0d --- /dev/null +++ b/springboot-starter1/src/main/java/com/jxy/HelloProperties.java @@ -0,0 +1,23 @@ +package com.jxy; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "bigboy") +public class HelloProperties { + private static final String DEFAULT_NAME = "江南一点雨"; + private static final String DEFAULT_MSG = "牧码小子"; + private String name = DEFAULT_NAME; + private String msg = DEFAULT_MSG; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getMsg() { + return msg; + } + public void setMsg(String msg) { + this.msg = msg; + } +} diff --git a/springboot-starter1/src/main/java/com/jxy/HelloService.java b/springboot-starter1/src/main/java/com/jxy/HelloService.java new file mode 100644 index 0000000000000000000000000000000000000000..cd271fc9fba6969350cf353caad6a2b4a9895392 --- /dev/null +++ b/springboot-starter1/src/main/java/com/jxy/HelloService.java @@ -0,0 +1,21 @@ +package com.jxy; + +public class HelloService { + private String msg; + private String name; + public String sayHello() { + return name + " say " + msg + " !"; + } + public String getMsg() { + return msg; + } + public void setMsg(String msg) { + this.msg = msg; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } +} diff --git a/springboot-starter1/src/main/java/com/jxy/HelloServiceAutoConfiguration.java b/springboot-starter1/src/main/java/com/jxy/HelloServiceAutoConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..28b5be395d079f753990c1c5d89968f48ebc3d10 --- /dev/null +++ b/springboot-starter1/src/main/java/com/jxy/HelloServiceAutoConfiguration.java @@ -0,0 +1,25 @@ +package com.jxy; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(HelloProperties.class) +@ConditionalOnClass(HelloService.class) +public class HelloServiceAutoConfiguration { + @Autowired + HelloProperties helloProperties; + + @Bean + @ConditionalOnMissingBean + HelloService helloService() { + HelloService helloService = new HelloService(); + helloService.setName(helloProperties.getName()); + helloService.setMsg(helloProperties.getMsg()); + return helloService; + } +} diff --git a/springboot-starter1/src/main/resources/META-INF/spring.factories b/springboot-starter1/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000000000000000000000000000000000..1969cda750d206bbbca484e367d578f2d3e335cc --- /dev/null +++ b/springboot-starter1/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.jxy.HelloServiceAutoConfiguration \ No newline at end of file diff --git a/springboot-transaction/src/main/java/com/xncoding/trans/service/UserService.java b/springboot-transaction/src/main/java/com/xncoding/trans/service/UserService.java index 00fa239ecb228a27124fe4fd0872674670c99bbc..4bf931aee273f3a12271216670a2cea4e13c11c7 100644 --- a/springboot-transaction/src/main/java/com/xncoding/trans/service/UserService.java +++ b/springboot-transaction/src/main/java/com/xncoding/trans/service/UserService.java @@ -11,6 +11,14 @@ import javax.annotation.Resource; @Service @Transactional(readOnly = true) public class UserService { + + /** + * @Transactional(readOnly = true) + * 应用场合: + * 如果你一次执行单条查询语句,则没有必要启用事务支持,数据库默认支持SQL执行期间的读一致性; + * 如果你一次执行多条查询语句,例如统计查询,报表查询,在这种场景下,多条查询SQL必须保证整体的读一致性,否则,在前条SQL查询之后,后条SQL查询之前,数据被其他用户改变,则该次整体的统计查询将会出现读数据不一致的状态,此时,应该启用事务支持。 + * 【注意是一次执行多次查询来统计某些信息,这时为了保证数据整体的一致性,要用只读事务】 + */ @Resource private UserMapper userMapper; @@ -28,6 +36,10 @@ public class UserService { errMethod(); // 执行一个会抛出异常的方法 } + /** + * noRollbackFor:属性‌用于指定在事务管理过程中,遇到哪些异常时不进行事务回滚。 + * rollbackFor:属性‌用于指定在事务管理过程中,遇到哪些异常时进行事务回滚。 + */ @Transactional(readOnly = false, noRollbackFor = {MyException.class}) public void updateUserError2(User user) { userMapper.updateById(user); diff --git a/springboot-transaction/src/main/resources/application.yml b/springboot-transaction/src/main/resources/application.yml index c9b5fa050fb71bbea5fff84f984bd40d7ebfbf25..10a3497df1f309eddba3a067d7651700c16f9a86 100644 --- a/springboot-transaction/src/main/resources/application.yml +++ b/springboot-transaction/src/main/resources/application.yml @@ -17,7 +17,7 @@ spring: datasource: url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8 username: root - password: 123456 + password: root ################### mybatis-plus配置 ################### mybatis-plus: diff --git a/springboot-websocket/src/main/java/com/xncoding/jwt/handler/SocketHandler.java b/springboot-websocket/src/main/java/com/xncoding/jwt/handler/SocketHandler.java index cab0da5f2357dbb7b47457e4f56259b9f73569ee..0e464586132765607ab3b20b8419a81ca161722e 100644 --- a/springboot-websocket/src/main/java/com/xncoding/jwt/handler/SocketHandler.java +++ b/springboot-websocket/src/main/java/com/xncoding/jwt/handler/SocketHandler.java @@ -39,7 +39,7 @@ public class SocketHandler extends TextWebSocketHandler { String msg = message.getPayload(); logger.info("msg = " + msg); WsParam wsParam = JacksonUtil.json2Bean(msg, new TypeReference>(){}); - if ("list".equals(wsParam.getMethod())) { + if (wsParam != null && "list".equals(wsParam.getMethod())) { logger.info("call list method..."); WsResponse response = new WsResponse<>(); response.setResult("hello list"); diff --git a/springboot-websocket/src/main/java/com/xncoding/jwt/model/RequestMessage.java b/springboot-websocket/src/main/java/com/xncoding/jwt/model/RequestMessage.java index 9f6e58dee20bd00fc6ae865ce6f9a2bf995f915a..170e0a36c3febff0e5cf039184dcadd52f998160 100644 --- a/springboot-websocket/src/main/java/com/xncoding/jwt/model/RequestMessage.java +++ b/springboot-websocket/src/main/java/com/xncoding/jwt/model/RequestMessage.java @@ -13,4 +13,8 @@ public class RequestMessage { public String getName() { return name; } + + public void setName(String name) { + this.name = name; + } }