├── .DS_Store ├── .gitignore ├── README.md ├── dump.rdb ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── .DS_Store ├── main ├── .DS_Store ├── java │ ├── .DS_Store │ └── com │ │ ├── .DS_Store │ │ └── gwf │ │ ├── .DS_Store │ │ └── family │ │ ├── .DS_Store │ │ ├── DruidStatFilter.java │ │ ├── DruidStatViewServlet.java │ │ ├── SpringBootMybatisWithRedisApplication.java │ │ ├── business │ │ ├── .DS_Store │ │ ├── code │ │ │ ├── controller │ │ │ │ └── CodeController.java │ │ │ ├── model │ │ │ │ ├── CodeSchema.java │ │ │ │ └── CodeTable.java │ │ │ └── service │ │ │ │ ├── CodeService.java │ │ │ │ └── impl │ │ │ │ └── CodeServiceImpl.java │ │ └── core │ │ │ ├── components │ │ │ └── JwtBean.java │ │ │ ├── controller │ │ │ └── AuthController.java │ │ │ ├── entity │ │ │ ├── IdEntity.java │ │ │ ├── JwtUser.java │ │ │ └── JwtUserFactory.java │ │ │ ├── exception │ │ │ └── ServiceException.java │ │ │ ├── mapper │ │ │ └── Mapper.java │ │ │ ├── results │ │ │ ├── AuthErrorEnum.java │ │ │ ├── Result.java │ │ │ ├── ResultCode.java │ │ │ ├── ResultEnum.java │ │ │ └── ResultGenerator.java │ │ │ ├── service │ │ │ ├── AbstractService.java │ │ │ ├── AuthService.java │ │ │ ├── AuthServiceImpl.java │ │ │ ├── JwtUserDetailServiceImpl.java │ │ │ └── Service.java │ │ │ └── util │ │ │ └── RedisCache.java │ │ ├── common │ │ ├── aop │ │ │ └── IdGenAspect.java │ │ ├── component │ │ │ └── FamilyDbUtils.java │ │ ├── model │ │ │ ├── DbColumnModel.java │ │ │ ├── DbModel.java │ │ │ ├── DbTableModel.java │ │ │ └── ProjectConstant.java │ │ └── util │ │ │ ├── ApplicationContextHolder.java │ │ │ ├── CookieUtil.java │ │ │ ├── DateUtil.java │ │ │ ├── IdGen.java │ │ │ ├── JwtUtil.java │ │ │ ├── KeyUtil.java │ │ │ ├── MathUtil.java │ │ │ ├── PropertiesLoader.java │ │ │ ├── ZipCompress.java │ │ │ └── serializer │ │ │ └── Date2LongSerializer.java │ │ ├── configurer │ │ ├── ControllerExceptionHandler.java │ │ ├── FreemarkerConfig.java │ │ ├── JwtAuthenticationTokenFilter.java │ │ ├── RestAuthenticationEntryPoint.java │ │ ├── WebMvcConfigurer.java │ │ └── WebSecurityConfig.java │ │ └── sys │ │ ├── role │ │ ├── controller │ │ │ └── SysRoleController.java │ │ ├── dao │ │ │ └── SysRoleRepository.java │ │ ├── entity │ │ │ └── SysRole.java │ │ └── service │ │ │ ├── SysRoleService.java │ │ │ └── impl │ │ │ └── SysRoleServiceImpl.java │ │ ├── user │ │ ├── controller │ │ │ └── SysUserController.java │ │ ├── dao │ │ │ └── SysUserRepository.java │ │ ├── entity │ │ │ └── SysUser.java │ │ └── service │ │ │ ├── SysUserService.java │ │ │ └── impl │ │ │ └── SysUserServiceImpl.java │ │ └── userroles │ │ ├── controller │ │ └── SysUserRolesController.java │ │ ├── dao │ │ └── SysUserRolesRepository.java │ │ ├── entity │ │ └── SysUserRoles.java │ │ └── service │ │ ├── SysUserRolesService.java │ │ └── impl │ │ └── SysUserRolesServiceImpl.java └── resources │ ├── application-dev.yml │ ├── application-pro.yml │ ├── application.yml │ ├── codeftl │ ├── controller.ftl │ ├── entity.ftl │ ├── mapper.ftl │ ├── repository.ftl │ ├── service.ftl │ └── serviceimpl.ftl │ ├── logback-spring.xml │ ├── mappers │ └── sys │ │ ├── role │ │ └── mapper │ │ │ └── SysRoleMapper.xml │ │ ├── user │ │ └── mapper │ │ │ └── SysUserMapper.xml │ │ └── userroles │ │ └── mapper │ │ └── SysUserRolesMapper.xml │ ├── static │ ├── connect.js │ └── jquery-1.7.2.min.js │ └── templates │ └── connect.ftl └── test ├── java └── com │ └── gwf │ └── family │ ├── SpringBootMybatisWithRedisApplicationTests.java │ └── business │ └── core │ └── service │ └── JwtUserDetailServiceImplTest.java └── resources └── sql ├── data.sql └── schema.sql /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-mybatis-with-redis 2 | spring-boot + mybatis + redis as second level cache 3 | 4 | 配置文件为application.yml。 5 | ### 1.将项目导入IntelliJ IDEA 6 | ### 2.打开src/main/resources下的application-dev.yml修改数据库及redis配置信息 7 | ### 3.启动SpringBootMybatisWithRedisApplication 8 | ### 4.浏览器访问localhost:9999/进入代码生成界面按照网页信息生成项目代码,并拷贝到工作目录 9 | -------------------------------------------------------------------------------- /dump.rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/dump.rdb -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.wooyoo.learning 7 | spring-boot-mybatis-with-redis 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-mybatis-with-redis 12 | Spring boot + mybatis + redis as second level cache 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-freemarker 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-redis 38 | 39 | 40 | 41 | 42 | org.mybatis.spring.boot 43 | mybatis-spring-boot-starter 44 | 1.3.0 45 | 46 | 47 | 48 | 49 | tk.mybatis 50 | mapper-spring-boot-starter 51 | 1.1.1 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-aop 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-security 64 | 65 | 66 | 67 | 68 | com.github.pagehelper 69 | pagehelper-spring-boot-starter 70 | 1.1.1 71 | 72 | 73 | 74 | 75 | mysql 76 | mysql-connector-java 77 | runtime 78 | 79 | 80 | 81 | 82 | org.springframework.boot 83 | spring-boot-starter-web 84 | 85 | 86 | 87 | 88 | com.alibaba 89 | fastjson 90 | 1.2.22 91 | 92 | 93 | 94 | 95 | commons-codec 96 | commons-codec 97 | 98 | 99 | org.apache.commons 100 | commons-lang3 101 | 3.5 102 | 103 | 104 | com.google.guava 105 | guava 106 | 22.0 107 | 108 | 109 | commons-fileupload 110 | commons-fileupload 111 | 1.3.1 112 | 113 | 114 | commons-io 115 | commons-io 116 | 2.4 117 | 118 | 119 | commons-beanutils 120 | commons-beanutils 121 | 1.9.2 122 | 123 | 124 | commons-logging 125 | commons-logging 126 | 1.2 127 | 128 | 129 | commons-lang 130 | commons-lang 131 | 2.6 132 | 133 | 134 | commons-collections 135 | commons-collections 136 | 3.2.2 137 | 138 | 139 | commons-logging 140 | commons-logging-api 141 | 1.1 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | com.alibaba 154 | druid-spring-boot-starter 155 | 1.1.0 156 | 157 | 158 | 159 | 160 | org.projectlombok 161 | lombok 162 | 1.16.16 163 | 164 | 165 | 166 | 167 | org.freemarker 168 | freemarker 169 | 2.3.23 170 | 171 | 172 | org.springframework 173 | spring-context-support 174 | 4.3.8.RELEASE 175 | 176 | 177 | 178 | org.apache.ant 179 | ant 180 | 1.9.0 181 | 182 | 183 | 184 | 185 | com.google.collections 186 | google-collections 187 | 1.0 188 | 189 | 190 | 191 | 192 | org.springframework 193 | spring-tx 194 | 4.3.9.RELEASE 195 | 196 | 197 | 198 | 199 | io.jsonwebtoken 200 | jjwt 201 | 0.6.0 202 | 203 | 204 | 205 | 206 | io.springfox 207 | springfox-swagger2 208 | 2.7.0 209 | 210 | 211 | io.springfox 212 | springfox-swagger-ui 213 | 2.7.0 214 | 215 | 216 | 217 | com.h2database 218 | h2 219 | test 220 | 221 | 222 | 223 | org.springframework.boot 224 | spring-boot-starter-test 225 | test 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | org.springframework.boot 235 | spring-boot-maven-plugin 236 | 237 | 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/.DS_Store -------------------------------------------------------------------------------- /src/main/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/.DS_Store -------------------------------------------------------------------------------- /src/main/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/java/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/java/com/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/gwf/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/java/com/gwf/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/java/com/gwf/family/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/DruidStatFilter.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family; 2 | 3 | import com.alibaba.druid.support.http.WebStatFilter; 4 | 5 | import javax.servlet.annotation.WebFilter; 6 | import javax.servlet.annotation.WebInitParam; 7 | 8 | /** 9 | * Created by gaowenfeng on 2017/8/3. 10 | */ 11 | @WebFilter(filterName="druidWebStatFilter",urlPatterns="/*", 12 | initParams={ 13 | @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源 14 | }) 15 | public class DruidStatFilter extends WebStatFilter { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/DruidStatViewServlet.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | 5 | import javax.servlet.annotation.WebInitParam; 6 | import javax.servlet.annotation.WebServlet; 7 | 8 | /** 9 | * Created by gaowenfeng on 2017/8/3. 10 | */ 11 | @SuppressWarnings("serial") 12 | @WebServlet(urlPatterns = "/druid/*", 13 | initParams={ 14 | @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问) 15 | @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow) 16 | @WebInitParam(name="loginUsername",value="shanhy"),// 用户名 17 | @WebInitParam(name="loginPassword",value="shanhypwd"),// 密码 18 | @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 19 | }) 20 | public class DruidStatViewServlet extends StatViewServlet { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/SpringBootMybatisWithRedisApplication.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 6 | import org.springframework.transaction.annotation.EnableTransactionManagement; 7 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 8 | 9 | @SpringBootApplication 10 | @EnableSwagger2 11 | public class SpringBootMybatisWithRedisApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringBootMybatisWithRedisApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/java/com/gwf/family/business/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/code/controller/CodeController.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.code.controller; 2 | 3 | 4 | import com.gwf.family.business.code.model.CodeSchema; 5 | import com.gwf.family.business.code.model.CodeTable; 6 | import com.gwf.family.business.code.service.CodeService; 7 | import com.gwf.family.business.core.exception.ServiceException; 8 | import com.gwf.family.business.core.results.Result; 9 | import com.gwf.family.business.core.results.ResultGenerator; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Controller; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import javax.servlet.ServletOutputStream; 16 | import javax.servlet.http.HttpServletResponse; 17 | import java.io.File; 18 | import java.io.FileInputStream; 19 | import java.io.InputStream; 20 | import java.util.List; 21 | 22 | /** 23 | * Created by lcy on 17/6/28. 24 | */ 25 | @Controller 26 | @RequestMapping("/code") 27 | public class CodeController { 28 | 29 | 30 | @Autowired 31 | private CodeService codeServiceImpl; 32 | 33 | /** 34 | * 连接数据库 schema 35 | * @param codeSchema 36 | * @return 37 | */ 38 | @RequestMapping("connectDb") 39 | @ResponseBody 40 | public Result connectDb(CodeSchema codeSchema){ 41 | List result = codeServiceImpl.getCodeTablesBySchema(codeSchema); 42 | return ResultGenerator.genSuccessResult(result); 43 | } 44 | 45 | /** 46 | * 导出code package 47 | * @return 48 | */ 49 | @RequestMapping(value = "constructCode") 50 | @ResponseBody // springMVC 下载 报页面找不到 51 | public void constructCode(CodeSchema codeSchema, HttpServletResponse response) throws Exception { 52 | ServletOutputStream out = null; 53 | InputStream fin = null; 54 | File file = null; 55 | String path = codeServiceImpl.generateCode(codeSchema); 56 | try{ 57 | if(null == path) 58 | return ; 59 | file = new File(path); 60 | //不存在 61 | if(null == file || !file.exists()) 62 | return ; 63 | // response 64 | response.setCharacterEncoding("utf-8"); 65 | response.setContentType("application/force-download"); 66 | response.addHeader("Content-Disposition", "attachment;filename=cyCode.zip"); 67 | out = response.getOutputStream(); 68 | fin = new FileInputStream(file); 69 | byte[] buffer = new byte[1024];//缓冲区 70 | int bytesToRead = -1; 71 | // 通过循环将读入的Word文件的内容输出到浏览器中 72 | while((bytesToRead = fin.read(buffer)) != -1) { 73 | out.write(buffer, 0, bytesToRead); 74 | } 75 | }catch(Exception ex){ 76 | throw new ServiceException("下载失败!"); 77 | }finally{ 78 | if(fin != null) fin.close(); 79 | if(out != null) out.close(); 80 | file.deleteOnExit(); 81 | } 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/code/model/CodeSchema.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.code.model; 2 | 3 | 4 | 5 | 6 | import com.gwf.family.common.model.DbModel; 7 | import lombok.Data; 8 | 9 | import java.io.Serializable; 10 | 11 | /** 12 | * Created by lcy on 17/7/1. 13 | * 14 | * code schema 15 | */ 16 | @Data 17 | public class CodeSchema implements Serializable { 18 | private static final long serialVersionUID = 1154645476624841358L; 19 | 20 | private String ip; 21 | 22 | private String db; 23 | 24 | private String url; 25 | 26 | private String dbName; 27 | 28 | private String username; 29 | 30 | private String password; 31 | 32 | private String port; 33 | 34 | private String dbProduct; 35 | 36 | private String driverClass; 37 | 38 | private String basePackage; 39 | 40 | private String author; 41 | 42 | private String tables; 43 | 44 | private String userId; 45 | 46 | public static long getSerialVersionUID() { 47 | return serialVersionUID; 48 | } 49 | 50 | 51 | public CodeSchema() { 52 | } 53 | 54 | public String getUrl() { 55 | if(DbModel.MYSQL.getType().equals(getDb())) 56 | return "jdbc:mysql://" + getIp() + ":" + getPort() + "/" + getDbName(); 57 | return url; 58 | } 59 | 60 | public String getDriverClass() { 61 | if(DbModel.MYSQL.getType().equals(getDb())) 62 | return "com.mysql.jdbc.Driver"; 63 | return driverClass; 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/code/model/CodeTable.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.code.model; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created by lcy on 17/7/1. 10 | * 11 | * code table 12 | */ 13 | @Data 14 | @NoArgsConstructor 15 | public class CodeTable implements Serializable { 16 | 17 | 18 | private static final long serialVersionUID = 1154645476624841358L; 19 | 20 | private String tableName; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/code/service/CodeService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.code.service; 2 | 3 | 4 | import com.gwf.family.business.code.model.CodeSchema; 5 | import com.gwf.family.business.code.model.CodeTable; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Created by lcy on 17/6/28. 11 | */ 12 | public interface CodeService { 13 | 14 | 15 | /** 16 | * 获取 codesTable 通过 schema 17 | * @param schema 18 | * @return 19 | */ 20 | public List getCodeTablesBySchema(CodeSchema schema); 21 | 22 | /** 23 | * 构建代码库 24 | * @param codeSchema 25 | * @return 26 | */ 27 | String generateCode(CodeSchema codeSchema) throws Exception; 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/code/service/impl/CodeServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.code.service.impl; 2 | 3 | 4 | import com.gwf.family.business.code.model.CodeSchema; 5 | import com.gwf.family.business.code.model.CodeTable; 6 | import com.gwf.family.business.code.service.CodeService; 7 | import com.gwf.family.business.core.exception.ServiceException; 8 | import com.gwf.family.common.component.FamilyDbUtils; 9 | import com.gwf.family.common.model.DbColumnModel; 10 | import com.gwf.family.common.model.DbTableModel; 11 | import com.gwf.family.common.model.ProjectConstant; 12 | import com.gwf.family.common.util.DateUtil; 13 | import com.gwf.family.common.util.ZipCompress; 14 | import freemarker.template.Configuration; 15 | import freemarker.template.Template; 16 | import lombok.extern.slf4j.Slf4j; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.transaction.annotation.Propagation; 20 | import org.springframework.transaction.annotation.Transactional; 21 | 22 | import javax.servlet.http.HttpServletRequest; 23 | import java.io.*; 24 | import java.sql.Connection; 25 | import java.sql.DatabaseMetaData; 26 | import java.sql.ResultSet; 27 | import java.sql.SQLException; 28 | import java.util.*; 29 | 30 | 31 | /** 32 | * Created by lcy on 17/6/28. 33 | */ 34 | @Service 35 | @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) 36 | @Slf4j 37 | public class CodeServiceImpl implements CodeService { 38 | private static final long serialVersionUID = -3827321264317955429L; 39 | private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径 40 | private static final String JAVA_PATH = "/src/main/java"; //java文件路径 41 | @Autowired 42 | private FamilyDbUtils familyDbUtils; 43 | @Autowired 44 | private HttpServletRequest request; 45 | @Autowired 46 | private Configuration freemarkerConfiguration; 47 | 48 | 49 | public List getCodeTablesBySchema(CodeSchema schema) { 50 | List tables = new ArrayList<>(); 51 | Connection conn = familyDbUtils.getConnection(schema); 52 | ResultSet rs = null; 53 | DatabaseMetaData dbmd = null; 54 | CodeTable ct = null; 55 | 56 | try { 57 | dbmd = (DatabaseMetaData) conn.getMetaData(); 58 | rs = (ResultSet) dbmd.getTables(null, schema.getDbName(), "%", null); 59 | while (rs.next()) { 60 | ct = new CodeTable(); 61 | ct.setTableName(rs.getString("TABLE_NAME")); 62 | tables.add(ct); 63 | } 64 | } catch (Exception e) { 65 | throw new ServiceException("数据库连接信息错误,或数据库不存在数据表!"); 66 | } finally { 67 | this.killConnection(rs, conn); 68 | } 69 | return tables; 70 | } 71 | 72 | @Override 73 | public String generateCode(CodeSchema codeSchema) throws Exception { 74 | String filePath = null; 75 | List tableModels = new ArrayList(); 76 | List models = null; 77 | ResultSet rs = null; 78 | DatabaseMetaData dbmd = null; 79 | CodeTable ct = null; 80 | DbTableModel tableModel = null; 81 | DbColumnModel model = null; 82 | Connection conn = familyDbUtils.getConnection(codeSchema); 83 | 84 | if (null == codeSchema.getTables() && "".equals(codeSchema.getTables().trim())) 85 | throw new ServiceException("没有选择任何表!"); 86 | if (conn == null) 87 | throw new ServiceException("数据库连接错误!"); 88 | 89 | String[] tables = codeSchema.getTables().split(","); 90 | 91 | try { 92 | dbmd = (DatabaseMetaData) conn.getMetaData(); 93 | for (String table : tables) { 94 | // table 95 | tableModel = new DbTableModel(); 96 | models = new ArrayList(); 97 | tableModel.setTableName(table.toLowerCase()); 98 | rs = (ResultSet) dbmd.getTables(null, codeSchema.getDbName(), table, new String[] { "TABLE" }); 99 | while (rs.next()) { 100 | if(rs.getString("TABLE_NAME").equals(table)){ 101 | String remarks = rs.getString("REMARKS"); 102 | // String remarks = rs.getString("REMARKS"); 103 | tableModel.setRemarks(remarks); 104 | } 105 | } 106 | //column 107 | rs = (ResultSet) dbmd.getColumns(null, codeSchema.getDbName(), table.toLowerCase(), null); 108 | dbmd.getPrimaryKeys(null, null, tables[0].toLowerCase()); 109 | while (rs.next()) { 110 | model = new DbColumnModel(); 111 | model.copyColumnFromSqlResult(rs); 112 | models.add(model); 113 | } 114 | rs = (ResultSet) dbmd.getPrimaryKeys(null, codeSchema.getDbName(), table.toLowerCase()); 115 | while (rs.next()) { 116 | String column = rs.getString("COLUMN_NAME"); 117 | for (DbColumnModel cm : models) { 118 | if (column.equals(cm.getColName())) { 119 | cm.setKey(true); 120 | break; 121 | } 122 | } 123 | } 124 | //table -> column 125 | tableModel.setColumnModels(models); 126 | tableModels.add(tableModel); 127 | } 128 | } catch (Exception e) { 129 | throw new ServiceException("生成表模型错误", e); 130 | } finally { 131 | this.killConnection(rs, conn); 132 | } 133 | filePath = this.productCodeFromTable(codeSchema.getAuthor(), codeSchema.getUserId(), codeSchema.getBasePackage(), tableModels); 134 | return filePath; 135 | } 136 | 137 | /** 138 | * 通过freemarker 成功多层代码 139 | * 140 | * @param tableModels 141 | * @return 142 | */ 143 | private String productCodeFromTable(String author, 144 | String userId, 145 | String packageName, 146 | List tableModels) 147 | throws Exception { 148 | Map root = null; 149 | List fileList = new ArrayList(); 150 | File file = null; 151 | String dirPath = request.getServletContext().getRealPath("code_generate_location") + 152 | File.separator + userId + 153 | File.separator + DateUtil.getSimepleDate("yyyyMMddHHmmss", new Date()); 154 | String zipPath = dirPath + ".zip"; 155 | String zipDirPath = dirPath; 156 | //将. 换/ 157 | String pathPattern = packageName.replaceAll("\\.", "\\" + File.separator); 158 | //存在删除 159 | dirPath = dirPath + File.separator + pathPattern; //!! 此行一定要在 zipPath 生成后 160 | File dirF = new File(dirPath); 161 | File zipFile = new File(zipPath); 162 | dirF.deleteOnExit(); 163 | zipFile.deleteOnExit(); 164 | //生成 165 | for (DbTableModel dbTableModel : tableModels) { 166 | root = new HashMap(); 167 | String basePackage = packageName + "." + dbTableModel.getEntityName().toLowerCase(); 168 | root.put("author", author); 169 | root.put("basePackage", basePackage); 170 | root.put("corePackage", ProjectConstant.BASE_PACKAGE); 171 | root.put("table", dbTableModel); 172 | //通过一个文件输出流,就可以写到相应的文件中 173 | //1.entity , mapper 174 | String newPath = dirPath + File.separator + dbTableModel.getEntityName().toLowerCase(); 175 | file = this.generateEntityModel(newPath, dbTableModel, root, "Entity"); 176 | fileList.add(file); 177 | 178 | file = this.generateEntityModel(newPath, dbTableModel, root, "Mapper"); 179 | fileList.add(file); 180 | //2.service 181 | file = this.generateEntityModel(newPath, dbTableModel, root, "Service"); 182 | fileList.add(file); 183 | //3.serviceImpl 184 | file = this.generateEntityModel(newPath, dbTableModel, root, "ServiceImpl"); 185 | fileList.add(file); 186 | //4.dao 187 | file = this.generateEntityModel(newPath, dbTableModel, root, "Repository"); 188 | fileList.add(file); 189 | //5.controller 190 | file = this.generateEntityModel(newPath, dbTableModel, root, "Controller"); 191 | fileList.add(file); 192 | //6.list jsp 193 | 194 | //7.list js 195 | 196 | //8.add jsp 197 | 198 | //9.add js 199 | 200 | //10.core code 201 | // genCoreCode(fileList, dirPath); 202 | } 203 | ZipCompress.compressExe(zipDirPath, zipPath); 204 | return zipPath; 205 | } 206 | 207 | /** 208 | * 关闭 connection 209 | * 210 | * @param rs 211 | * @param conn 212 | */ 213 | private void killConnection(ResultSet rs, Connection conn) { 214 | try { 215 | if (null != rs) 216 | rs.close(); 217 | if (null != conn) 218 | conn.close(); 219 | } catch (SQLException e) { 220 | log.error(e.getMessage()); 221 | } 222 | } 223 | 224 | /** 225 | * model 构建 entity 层 226 | * 227 | * @param dirPath 228 | * @param dbTableModel 229 | * @param root 230 | * @return 231 | */ 232 | private File generateEntityModel(String dirPath, DbTableModel dbTableModel, Map root, String suffix) throws Exception { 233 | //源文件夹 234 | File dirFile = null; 235 | //目标文件 236 | File file = null; 237 | FileWriter out = null; 238 | Template temp = null; 239 | if (suffix.equals("Repository")) 240 | dirFile = new File(dirPath + File.separator + "dao"); 241 | else if (suffix.equals("ServiceImpl")) 242 | dirFile = new File(dirPath + File.separator + "service" + File.separator + "impl"); 243 | else 244 | dirFile = new File(dirPath + File.separator + suffix.toLowerCase()); 245 | //不存在 创建文件夹 246 | if (!dirFile.exists()) 247 | dirFile.mkdirs(); 248 | if (suffix.equals("Repository")) 249 | file = new File(dirPath + File.separator + "dao" + 250 | File.separator + dbTableModel.getEntityName() + suffix + ".java"); 251 | else if (suffix.equals("ServiceImpl")) 252 | file = new File(dirPath + File.separator + "service" + File.separator + "impl" + 253 | File.separator + dbTableModel.getEntityName() + suffix + ".java"); 254 | else if (suffix.equals("Entity")) 255 | file = new File(dirPath + File.separator + suffix.toLowerCase() + 256 | File.separator + dbTableModel.getEntityName() + ".java"); 257 | else if (suffix.equals("Mapper")) 258 | file = new File(dirPath + File.separator + suffix.toLowerCase() + 259 | File.separator + dbTableModel.getEntityName() + suffix + ".xml"); 260 | else 261 | file = new File(dirPath + File.separator + suffix.toLowerCase() + 262 | File.separator + dbTableModel.getEntityName() + suffix + ".java"); 263 | try { 264 | out = new FileWriter(file); 265 | //fileList.add(file); 266 | temp = freemarkerConfiguration.getTemplate(suffix.toLowerCase() + ".ftl"); 267 | temp.process(root, out); 268 | } finally { 269 | try { 270 | if (out != null) 271 | out.close(); 272 | } catch (IOException e) { 273 | e.printStackTrace(); 274 | } 275 | 276 | } 277 | return file; 278 | } 279 | 280 | private void genCoreCode(List fileList, String dirPath) throws Exception { 281 | File dir = new File(PROJECT_PATH + JAVA_PATH + "/com/gwf/core/business/core"); 282 | 283 | dirPath+=File.separator+"core"; 284 | foreachDir(dir, fileList, dirPath); 285 | } 286 | 287 | private void foreachDir(File dir, List fileList, String dirPath) throws Exception { 288 | File[] listFiles = dir.listFiles(); 289 | 290 | for (File f : listFiles) { 291 | 292 | File file = null; 293 | File fileDir = null; 294 | if (f.isDirectory()) { 295 | String newPath = dirPath + File.separator + f.getName(); 296 | foreachDir(f, fileList, newPath); 297 | } else { 298 | InputStreamReader reader = null; 299 | OutputStreamWriter writer = null; 300 | try { 301 | fileDir = new File(dirPath + File.separator ); 302 | file = new File(dirPath + File.separator + File.separator + f.getName()); 303 | if (!fileDir.exists()) 304 | fileDir.mkdirs(); 305 | if (!file.exists()) 306 | file.createNewFile(); 307 | reader = new InputStreamReader(new FileInputStream(f)); 308 | writer = new OutputStreamWriter(new FileOutputStream(file)); 309 | char[] buffer = new char[1024]; 310 | int len; 311 | while ((len =reader.read(buffer)) != -1) 312 | writer.write(buffer,0,len); 313 | fileList.add(file); 314 | } finally { 315 | try { 316 | reader.close(); 317 | writer.close(); 318 | } catch (IOException e) { 319 | e.printStackTrace(); 320 | } 321 | } 322 | } 323 | } 324 | } 325 | 326 | } 327 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/components/JwtBean.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.components; 2 | 3 | import io.jsonwebtoken.Claims; 4 | import io.jsonwebtoken.Jwts; 5 | import io.jsonwebtoken.SignatureAlgorithm; 6 | import lombok.Data; 7 | import lombok.Setter; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.Date; 12 | import java.util.Map; 13 | 14 | /** 15 | * Created by gaowenfeng on 2017/8/9. 16 | */ 17 | 18 | public class JwtBean { 19 | 20 | @Value("${jwt.secret}") 21 | private String secret; 22 | 23 | 24 | /** 25 | * 根据token获取用户信息 26 | */ 27 | public Claims getClaimsFromToken(String token){ 28 | try { 29 | Claims claims = Jwts.parser() 30 | .setSigningKey(secret) 31 | .parseClaimsJws(token).getBody(); 32 | return claims; 33 | }catch (Exception e){ 34 | return null; 35 | } 36 | } 37 | 38 | /** 39 | * 设置用户信息进jwt 40 | */ 41 | public String generateToken(String subject, Map map){ 42 | String token = Jwts 43 | .builder() 44 | .setClaims(map) 45 | .setSubject(subject) 46 | .setIssuedAt(new Date()) 47 | .signWith(SignatureAlgorithm.HS256, secret) 48 | .compact(); 49 | return token; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.controller; 2 | 3 | import com.gwf.family.business.core.results.Result; 4 | import com.gwf.family.business.core.results.ResultGenerator; 5 | import com.gwf.family.business.core.service.AuthService; 6 | import com.gwf.family.sys.user.entity.SysUser; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | 17 | /** 18 | * Created by gaowenfeng on 2017/8/9. 19 | */ 20 | @RestController 21 | public class AuthController { 22 | @Value("${jwt.header}") 23 | private String tokenHeader; 24 | 25 | @Autowired 26 | private AuthService authService; 27 | 28 | @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) 29 | public Result createAuthenticationToken(@RequestParam("username")String username, 30 | @RequestParam("password")String password){ 31 | final String token = authService.login(username, password); 32 | return ResultGenerator.genSuccessResult(token); 33 | } 34 | 35 | @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET) 36 | public Result refreshAndGetAuthenticationToken( 37 | HttpServletRequest request){ 38 | String token = request.getHeader(tokenHeader); 39 | String refreshedToken = authService.refresh(token); 40 | if(refreshedToken == null) { 41 | return ResultGenerator.genSuccessResult(); 42 | } else { 43 | return ResultGenerator.genSuccessResult(refreshedToken); 44 | } 45 | } 46 | 47 | @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST) 48 | public Result register(SysUser addedUser){ 49 | authService.register(addedUser); 50 | return ResultGenerator.genSuccessResult(); 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/entity/IdEntity.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.entity; 2 | 3 | /** 4 | * Created by gaowenfeng on 2017/9/27. 5 | */ 6 | public interface IdEntity { 7 | void setBusinessId(String id); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/entity/JwtUser.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.entity; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import lombok.Data; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | 8 | import java.util.Collection; 9 | 10 | /** 11 | * Created by gwf on 2017/8/9. 12 | * security需要的UserDetails实现类 13 | */ 14 | @Data 15 | public class JwtUser implements UserDetails { 16 | private static final long serialVersionUID = -4959252432107932674L; 17 | private final long id; 18 | private final String username; 19 | private final String password; 20 | /** 权限类.*/ 21 | private final Collection authorities; 22 | 23 | /** 24 | * 在createJwtFactory里注入 25 | */ 26 | public JwtUser(long id, 27 | String username, 28 | String password, 29 | Collection authorities) { 30 | this.id = id; 31 | this.username = username; 32 | this.password = password; 33 | this.authorities = authorities; 34 | } 35 | 36 | @Override 37 | public Collection getAuthorities() { 38 | return authorities; 39 | } 40 | 41 | @Override 42 | @JsonIgnore 43 | public String getPassword() { 44 | return password; 45 | } 46 | 47 | @Override 48 | public String getUsername() { 49 | return username; 50 | } 51 | 52 | @Override 53 | @JsonIgnore 54 | public boolean isAccountNonExpired() { 55 | return true; 56 | } 57 | 58 | @Override 59 | @JsonIgnore 60 | public boolean isAccountNonLocked() { 61 | return true; 62 | } 63 | 64 | @Override 65 | @JsonIgnore 66 | public boolean isCredentialsNonExpired() { 67 | return true; 68 | } 69 | 70 | @Override 71 | @JsonIgnore 72 | public boolean isEnabled() { 73 | return true; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/entity/JwtUserFactory.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.entity; 2 | 3 | import com.gwf.family.sys.role.entity.SysRole; 4 | import com.gwf.family.sys.user.entity.SysUser; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 7 | 8 | import java.util.List; 9 | import java.util.stream.Collectors; 10 | 11 | /** 12 | * Created by gaowenfeng on 2017/8/9. 13 | */ 14 | public final class JwtUserFactory { 15 | 16 | private JwtUserFactory() { 17 | } 18 | 19 | /** 20 | * 创建JwtUser工厂 21 | */ 22 | public static JwtUser create(SysUser user){ 23 | return new JwtUser( 24 | user.getId(), 25 | user.getUsername(), 26 | user.getPassword(), 27 | map2GrantedAuthorities(user.getRoles()) 28 | ); 29 | } 30 | 31 | /** 32 | * 讲User的List转换成JwtUser 33 | */ 34 | private static List map2GrantedAuthorities(List authorities){ 35 | return authorities.stream() 36 | .map(e -> role2SimpleGrantedAuthority(e)) 37 | .collect(Collectors.toList()); 38 | } 39 | 40 | private static SimpleGrantedAuthority role2SimpleGrantedAuthority(SysRole role){ 41 | return new SimpleGrantedAuthority(role.getName()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/exception/ServiceException.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.exception; 2 | 3 | import com.gwf.family.business.core.results.ResultEnum; 4 | 5 | /** 6 | * 服务(业务)异常如“ 账号或密码错误 ”,该异常只做INFO级别的日志记录 @see WebMvcConfigurer 7 | */ 8 | public class ServiceException extends RuntimeException { 9 | private static final long serialVersionUID = 3729706443523052156L; 10 | 11 | public ServiceException() { 12 | } 13 | 14 | public ServiceException(ResultEnum resultEnum){ 15 | super(resultEnum.getMessage()); 16 | } 17 | 18 | public ServiceException(String message) { 19 | super(message); 20 | } 21 | 22 | public ServiceException(String message, Throwable cause) { 23 | super(message, cause); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/mapper/Mapper.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.mapper; 2 | 3 | import tk.mybatis.mapper.common.BaseMapper; 4 | import tk.mybatis.mapper.common.ConditionMapper; 5 | import tk.mybatis.mapper.common.IdsMapper; 6 | import tk.mybatis.mapper.common.special.InsertListMapper; 7 | 8 | /** 9 | * 定制版MyBatis Mapper插件接口,如需其他接口参考官方文档自行添加。 10 | */ 11 | public interface Mapper 12 | extends 13 | BaseMapper, 14 | ConditionMapper, 15 | IdsMapper, 16 | InsertListMapper { 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/results/AuthErrorEnum.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.results; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * Created by gaowenfeng on 2017/8/9. 7 | */ 8 | @Getter 9 | public enum AuthErrorEnum { 10 | ACCESS_DENIED(4031,"权限不足"), 11 | LOGIN_PARAM_ERROR(4302,"用户名密码错误"), 12 | AUTH_HEADER_ERROR(4304,"不合法的token验证"), 13 | ; 14 | 15 | private Integer code; 16 | private String message; 17 | 18 | AuthErrorEnum(Integer code, String message) { 19 | this.code = code; 20 | this.message = message; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/results/Result.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.results; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | 5 | /** 6 | * 统一API响应结果封装 7 | */ 8 | public class Result { 9 | private int code; 10 | private String message; 11 | private Object data; 12 | 13 | public Result setCode(ResultCode resultCode) { 14 | this.code = resultCode.code; 15 | return this; 16 | } 17 | 18 | public int getCode() { 19 | return code; 20 | } 21 | 22 | public Result setCode(int code) { 23 | this.code = code; 24 | return this; 25 | } 26 | 27 | public String getMessage() { 28 | return message; 29 | } 30 | 31 | public Result setMessage(String message) { 32 | this.message = message; 33 | return this; 34 | } 35 | 36 | public Object getData() { 37 | return data; 38 | } 39 | 40 | public Result setData(Object data) { 41 | this.data = data; 42 | return this; 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return JSON.toJSONString(this); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/results/ResultCode.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.results; 2 | 3 | /** 4 | * 响应码枚举,参考HTTP状态码的语义 5 | */ 6 | public enum ResultCode { 7 | SUCCESS(200),//成功 8 | FAIL(400),//失败 9 | UNAUTHORIZED(401),//未认证(签名错误) 10 | NOT_FOUND(404),//接口不存在 11 | INTERNAL_SERVER_ERROR(500);//服务器内部错误 12 | 13 | public int code; 14 | 15 | ResultCode(int code) { 16 | this.code = code; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/results/ResultEnum.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.results; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * Created by gaowenfeng on 2017/8/10. 7 | */ 8 | @Getter 9 | public enum ResultEnum { 10 | USER_EXISTS(4001,"用户已经存在"), 11 | USER_NOT_EXISTS(4002,"用户不存在"), 12 | SAVE_ERROR(4003,"添加失败"), 13 | ; 14 | 15 | private Integer code; 16 | private String message; 17 | 18 | ResultEnum(Integer code, String message) { 19 | this.code = code; 20 | this.message = message; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/results/ResultGenerator.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.results; 2 | 3 | /** 4 | * 响应结果生成工具 5 | */ 6 | public class ResultGenerator { 7 | private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS"; 8 | 9 | public static Result genSuccessResult() { 10 | return new Result() 11 | .setCode(ResultCode.SUCCESS) 12 | .setMessage(DEFAULT_SUCCESS_MESSAGE); 13 | } 14 | 15 | public static Result genSuccessResult(Object data) { 16 | return new Result() 17 | .setCode(ResultCode.SUCCESS) 18 | .setMessage(DEFAULT_SUCCESS_MESSAGE) 19 | .setData(data); 20 | } 21 | 22 | public static Result genFailResult(String message) { 23 | return new Result() 24 | .setCode(ResultCode.FAIL) 25 | .setMessage(message); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/service/AbstractService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | 4 | import com.gwf.family.business.core.exception.ServiceException; 5 | import com.gwf.family.business.core.mapper.Mapper; 6 | import org.apache.ibatis.exceptions.TooManyResultsException; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import tk.mybatis.mapper.entity.Condition; 9 | 10 | import java.lang.reflect.Field; 11 | import java.lang.reflect.ParameterizedType; 12 | import java.util.List; 13 | 14 | /** 15 | * 基于通用MyBatis Mapper插件的Service接口的实现 16 | */ 17 | public abstract class AbstractService implements Service { 18 | 19 | @Autowired 20 | protected Mapper mapper; 21 | 22 | private Class modelClass; // 当前泛型真实类型的Class 23 | 24 | public AbstractService() { 25 | ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); 26 | modelClass = (Class) pt.getActualTypeArguments()[0]; 27 | } 28 | 29 | public void save(T model) { 30 | mapper.insertSelective(model); 31 | } 32 | 33 | public void save(List models) { 34 | mapper.insertList(models); 35 | } 36 | 37 | public void deleteById(Object id) { 38 | mapper.deleteByPrimaryKey(id); 39 | } 40 | 41 | public void deleteByIds(String ids) { 42 | mapper.deleteByIds(ids); 43 | } 44 | 45 | public void update(T model) { 46 | mapper.updateByPrimaryKeySelective(model); 47 | } 48 | 49 | public T findById(Object id) { 50 | return mapper.selectByPrimaryKey(id); 51 | } 52 | 53 | @Override 54 | public T findBy(String fieldName, Object value) throws TooManyResultsException { 55 | try { 56 | T model = modelClass.newInstance(); 57 | Field field = modelClass.getDeclaredField(fieldName); 58 | field.setAccessible(true); 59 | field.set(model, value); 60 | return mapper.selectOne(model); 61 | } catch (ReflectiveOperationException e) { 62 | throw new ServiceException(e.getMessage(), e); 63 | } 64 | } 65 | 66 | public List findByIds(String ids) { 67 | return mapper.selectByIds(ids); 68 | } 69 | 70 | public List findByCondition(Condition condition) { 71 | return mapper.selectByCondition(condition); 72 | } 73 | 74 | public List findAll() { 75 | return mapper.selectAll(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/service/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | 4 | import com.gwf.family.sys.user.entity.SysUser; 5 | 6 | /** 7 | * Created by gaowenfeng on 2017/8/9. 8 | */ 9 | public interface AuthService { 10 | void register(SysUser userToAdd); 11 | String login(String username, String password); 12 | String refresh(String oldToken); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/service/AuthServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | import com.gwf.family.business.core.exception.ServiceException; 4 | import com.gwf.family.business.core.results.ResultEnum; 5 | import com.gwf.family.common.util.JwtUtil; 6 | import com.gwf.family.sys.user.dao.SysUserRepository; 7 | import com.gwf.family.sys.user.entity.SysUser; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.context.SecurityContextHolder; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | import org.springframework.security.core.userdetails.UserDetailsService; 16 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 17 | import org.springframework.security.crypto.password.PasswordEncoder; 18 | import org.springframework.stereotype.Service; 19 | 20 | 21 | /** 22 | * Created by gaowenfeng on 2017/8/9. 23 | */ 24 | @Service 25 | public class AuthServiceImpl implements AuthService{ 26 | private AuthenticationManager authenticationManager; 27 | private UserDetailsService userDetailsService; 28 | private SysUserRepository userRepository; 29 | private PasswordEncoder passwordEncoder; 30 | 31 | @Autowired 32 | public AuthServiceImpl(AuthenticationManager authenticationManager, 33 | UserDetailsService userDetailsService, 34 | SysUserRepository userRepository, 35 | PasswordEncoder passwordEncoder) { 36 | this.authenticationManager = authenticationManager; 37 | this.userDetailsService = userDetailsService; 38 | this.userRepository = userRepository; 39 | this.passwordEncoder = passwordEncoder; 40 | } 41 | 42 | @Value("${jwt.tokenHead}") 43 | private String tokenHead; 44 | 45 | @Override 46 | public void register(SysUser userToAdd) { 47 | if(userRepository.findByUserName(userToAdd.getUsername())!=null) 48 | throw new ServiceException(ResultEnum.USER_EXISTS); 49 | userToAdd.setPassword(passwordEncoder.encode(userToAdd.getPassword())); 50 | int result = userRepository.insertSelective(userToAdd); 51 | if(result==0) 52 | throw new ServiceException(ResultEnum.SAVE_ERROR); 53 | } 54 | 55 | @Override 56 | public String login(String username, String password) { 57 | UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password); 58 | final Authentication authentication = authenticationManager.authenticate(upToken); 59 | SecurityContextHolder.getContext().setAuthentication(authentication); 60 | 61 | final UserDetails userDetails = userDetailsService.loadUserByUsername(username); 62 | final String token = JwtUtil.generateToken(userDetails); 63 | return token; 64 | } 65 | 66 | @Override 67 | public String refresh(String oldToken) { 68 | return null; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/service/JwtUserDetailServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | import com.gwf.family.business.core.entity.JwtUserFactory; 4 | import com.gwf.family.sys.role.dao.SysRoleRepository; 5 | import com.gwf.family.sys.role.entity.SysRole; 6 | import com.gwf.family.sys.user.dao.SysUserRepository; 7 | import com.gwf.family.sys.user.entity.SysUser; 8 | import lombok.Data; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.util.CollectionUtils; 14 | 15 | import java.util.Collections; 16 | import java.util.List; 17 | 18 | /** 19 | * Created by gaowenfeng on 2017/2/5. 20 | */ 21 | @Data 22 | @org.springframework.stereotype.Service 23 | public class JwtUserDetailServiceImpl implements UserDetailsService { 24 | 25 | @Autowired 26 | private SysUserRepository userRepository; 27 | @Autowired 28 | private SysRoleRepository sysRoleRepository; 29 | 30 | @Override 31 | public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { 32 | SysUser sysUser = userRepository.findByUserName(s); //调用持久层从数据库获取用户信息 33 | if (sysUser == null) 34 | throw new UsernameNotFoundException("用户名不存在"); 35 | List roles = sysRoleRepository.findRolesByUserId(sysUser.getId()); //根据用户id或者用户权限列表 36 | if (CollectionUtils.isEmpty(roles)) 37 | roles = Collections.emptyList(); 38 | sysUser.setRoles(roles); 39 | return JwtUserFactory.create(sysUser); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/service/Service.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | import org.apache.ibatis.exceptions.TooManyResultsException; 4 | import tk.mybatis.mapper.entity.Condition; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Service 层 基础接口,其他Service 接口 请继承该接口 10 | */ 11 | public interface Service { 12 | void save(T model);//持久化 13 | void save(List models);//批量持久化 14 | void deleteById(Object id);//通过主鍵刪除 15 | void deleteByIds(String ids);//批量刪除 eg:ids -> “1,2,3,4” 16 | void update(T model);//更新 17 | T findById(Object id);//通过ID查找 18 | T findBy(String fieldName, Object value) throws TooManyResultsException; //通过Model中某个成员变量名称(非数据表中column的名称)查找,value需符合unique约束 19 | List findByIds(String ids);//通过多个ID查找//eg:ids -> “1,2,3,4” 20 | List findByCondition(Condition condition);//根据条件查找 21 | List findAll();//获取所有 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/business/core/util/RedisCache.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.util; 2 | 3 | import com.gwf.family.common.util.ApplicationContextHolder; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.apache.ibatis.cache.Cache; 6 | import org.springframework.data.redis.core.RedisCallback; 7 | import org.springframework.data.redis.core.RedisTemplate; 8 | import org.springframework.data.redis.core.ValueOperations; 9 | 10 | import java.util.concurrent.TimeUnit; 11 | import java.util.concurrent.locks.ReadWriteLock; 12 | import java.util.concurrent.locks.ReentrantReadWriteLock; 13 | 14 | @Slf4j 15 | public class RedisCache implements Cache { 16 | 17 | private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 18 | private final String id; // cache instance id 19 | private RedisTemplate redisTemplate; 20 | 21 | private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间 22 | 23 | public RedisCache(String id) { 24 | if (id == null) { 25 | throw new IllegalArgumentException("Cache instances require an ID"); 26 | } 27 | this.id = id; 28 | } 29 | 30 | @Override 31 | public String getId() { 32 | return id; 33 | } 34 | 35 | /** 36 | * Put query result to redis 37 | * 38 | * @param key 39 | * @param value 40 | */ 41 | @Override 42 | @SuppressWarnings("unchecked") 43 | public void putObject(Object key, Object value) { 44 | try { 45 | RedisTemplate redisTemplate = getRedisTemplate(); 46 | ValueOperations opsForValue = redisTemplate.opsForValue(); 47 | opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES); 48 | log.debug("Put query result to redis"); 49 | } 50 | catch (Throwable t) { 51 | log.error("Redis put failed", t); 52 | } 53 | } 54 | 55 | /** 56 | * Get cached query result from redis 57 | * 58 | * @param key 59 | * @return 60 | */ 61 | @Override 62 | public Object getObject(Object key) { 63 | try { 64 | RedisTemplate redisTemplate = getRedisTemplate(); 65 | ValueOperations opsForValue = redisTemplate.opsForValue(); 66 | log.debug("Get cached query result from redis"); 67 | return opsForValue.get(key); 68 | } 69 | catch (Throwable t) { 70 | log.error("Redis get failed, fail over to db", t); 71 | return null; 72 | } 73 | } 74 | 75 | /** 76 | * Remove cached query result from redis 77 | * 78 | * @param key 79 | * @return 80 | */ 81 | @Override 82 | @SuppressWarnings("unchecked") 83 | public Object removeObject(Object key) { 84 | try { 85 | RedisTemplate redisTemplate = getRedisTemplate(); 86 | redisTemplate.delete(key); 87 | log.debug("Remove cached query result from redis"); 88 | } 89 | catch (Throwable t) { 90 | log.error("Redis remove failed", t); 91 | } 92 | return null; 93 | } 94 | 95 | /** 96 | * Clears this cache instance 97 | */ 98 | @Override 99 | public void clear() { 100 | RedisTemplate redisTemplate = getRedisTemplate(); 101 | redisTemplate.execute((RedisCallback) connection -> { 102 | connection.flushDb(); 103 | return null; 104 | }); 105 | log.debug("Clear all the cached query result from redis"); 106 | } 107 | 108 | /** 109 | * This method is not used 110 | * 111 | * @return 112 | */ 113 | @Override 114 | public int getSize() { 115 | return 0; 116 | } 117 | 118 | @Override 119 | public ReadWriteLock getReadWriteLock() { 120 | return readWriteLock; 121 | } 122 | 123 | private RedisTemplate getRedisTemplate() { 124 | if (redisTemplate == null) { 125 | redisTemplate = ApplicationContextHolder.getBean("redisTemplate"); 126 | } 127 | return redisTemplate; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/aop/IdGenAspect.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.aop; 2 | 3 | import com.gwf.family.business.core.entity.IdEntity; 4 | import com.gwf.family.common.util.IdGen; 5 | import org.aspectj.lang.JoinPoint; 6 | import org.aspectj.lang.annotation.Aspect; 7 | import org.aspectj.lang.annotation.Before; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | * Created by gaowenfeng on 2017/9/27. 12 | */ 13 | @Aspect 14 | @Component 15 | public class IdGenAspect { 16 | @Before("execution(* com.gwf.family.business..*.dao.*Repository.insert*(..))") 17 | public void beforeInsert(JoinPoint joinPoint){ 18 | Object model = joinPoint.getArgs()[0]; 19 | if(model instanceof IdEntity) 20 | ((IdEntity) model).setBusinessId(IdGen.uuid()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/component/FamilyDbUtils.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.component; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.gwf.family.business.code.model.CodeSchema; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.ibatis.mapping.Environment; 7 | import org.apache.ibatis.session.Configuration; 8 | import org.apache.ibatis.session.SqlSession; 9 | import org.apache.ibatis.session.SqlSessionFactory; 10 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 11 | import org.apache.ibatis.transaction.TransactionFactory; 12 | import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; 13 | import org.springframework.stereotype.Component; 14 | 15 | import java.sql.Connection; 16 | import java.sql.DriverManager; 17 | 18 | /** 19 | * Created by lcy on 17/6/30. 20 | */ 21 | @Component 22 | @Slf4j 23 | public class FamilyDbUtils { 24 | /** 25 | * 获取 连接 26 | * 27 | * 通过druidSource 获取连接 连接信息错误时,无法catch住,暂未解决,连接不会停止,不断尝试连接 28 | * 暂不使用 29 | * 30 | * @return 31 | * 32 | * select table_name from information_schema.tables where table_schema='csdb' and table_type='base table'; 33 | * 34 | * show tables; 35 | */ 36 | public SqlSession getConnectSession(CodeSchema schema){ 37 | // data source 38 | DruidDataSource ds = new DruidDataSource(); 39 | ds.setUrl("jdbc:mysql://" + schema.getUrl() + ":3306/" + schema.getDbName()); 40 | ds.setPassword(schema.getPassword()); 41 | ds.setUsername(schema.getUsername()); 42 | ds.setName(schema.getDbName()); 43 | ds.setDriverClassName("com.mysql.jdbc.Driver"); 44 | if(ds.isTestOnReturn()) { 45 | ds.close(); 46 | } 47 | //ds.setDriverClassName(""); 48 | //ds.setDriver(new DruidDriver()); 49 | // configure 50 | Configuration configuration = new Configuration(); 51 | TransactionFactory transactionFactory = new JdbcTransactionFactory(); 52 | Environment environment = new Environment(schema.getUsername(),transactionFactory,ds); 53 | configuration.setEnvironment(environment); 54 | SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); 55 | return sqlSessionFactory.openSession(); 56 | } 57 | 58 | 59 | /** 60 | * 通过jdbc 获取 connection 61 | * @param schema 62 | * @return 63 | */ 64 | public Connection getConnection(CodeSchema schema) { 65 | 66 | Connection con = null; 67 | try { 68 | Class.forName(schema.getDriverClass());//创建驱动器 69 | con = DriverManager.getConnection(schema.getUrl(), schema.getUsername(), schema.getPassword()); 70 | } catch (Exception e) { 71 | log.error(e.getMessage()); 72 | } 73 | return con; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/model/DbColumnModel.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.model; 2 | 3 | import lombok.Data; 4 | import org.springframework.util.StringUtils; 5 | 6 | import java.io.Serializable; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | 10 | /** 11 | * Created by lcy on 17/7/5. 12 | */ 13 | @Data 14 | public class DbColumnModel implements Serializable { 15 | private static final long serialVersionUID = -7808860348918160912L; 16 | 17 | 18 | public DbColumnModel() { 19 | } 20 | 21 | private String colName; //列名 22 | 23 | private String typeName; //类型名称 24 | 25 | private String typeNameUpper; //类型名称 26 | 27 | private String remarks; 28 | 29 | private int precision, isNull, dataType, scale; //精度,是否为空,类型,小数的位数 30 | 31 | private boolean isKey = false; //是否为主键 32 | 33 | private String columnNameLowerCamel; //列名转化为小写驼峰式 34 | 35 | private String columnNameUpperCamel; //列名转化为大写驼峰式 36 | 37 | private String javaType; //数据库属性名转化为java属性名 38 | 39 | public String getJavaType() { 40 | String typeNamel = typeName.toLowerCase(); 41 | switch (typeNamel) { 42 | case "int": 43 | javaType = "Integer"; 44 | break; 45 | case "varchar": 46 | javaType = "String"; 47 | break; 48 | case "char": 49 | javaType = "Char"; 50 | break; 51 | case "blob": 52 | javaType = "Byte[]"; 53 | break; 54 | case "text": 55 | javaType = "String"; 56 | break; 57 | case "integer": 58 | javaType = "Long"; 59 | break; 60 | case "tinyint": 61 | javaType = "Integer"; 62 | break; 63 | case "smallint": 64 | javaType = "Integer"; 65 | break; 66 | case "mediumint": 67 | javaType = "Integer"; 68 | break; 69 | case "bit": 70 | javaType = "Boolean"; 71 | break; 72 | case "bigint": 73 | javaType = "long"; 74 | break; 75 | case "float": 76 | javaType = "Float"; 77 | break; 78 | case "double": 79 | javaType = "Double"; 80 | break; 81 | case "decimal": 82 | javaType = "BigDecimal"; 83 | break; 84 | case "id": 85 | javaType = "Long"; 86 | break; 87 | case "date": 88 | javaType = "Date"; 89 | break; 90 | case "year": 91 | javaType = "Date"; 92 | break; 93 | case "time": 94 | javaType = "Date"; 95 | break; 96 | case "datetime": 97 | javaType = "Date"; 98 | break; 99 | case "timestamp": 100 | javaType = "Date"; 101 | break; 102 | case "smallint unsigned": 103 | javaType = "short"; 104 | break; 105 | case "tinyint unsigned": 106 | javaType = "Byte"; 107 | break; 108 | case "enum": 109 | javaType = "String"; 110 | break; 111 | case "set": 112 | javaType = "String"; 113 | break; 114 | } 115 | return javaType; 116 | } 117 | 118 | public String getColumnNameLowerCamel() { 119 | columnNameLowerCamel = columnNameConvertLowerCamel(colName); 120 | return columnNameLowerCamel; 121 | } 122 | 123 | 124 | public String getColumnNameUpperCamel() { 125 | columnNameUpperCamel = columnNameConvertUpperCamel(colName); 126 | return columnNameUpperCamel; 127 | } 128 | 129 | /** 130 | * 将数据库属性名改为驼峰式,首字母大写 131 | * 132 | * @param columnName 列名 133 | * @return 134 | */ 135 | private static String columnNameConvertLowerCamel(String columnName) { 136 | StringBuilder result = new StringBuilder(); 137 | if (columnName != null && columnName.length() > 0) { 138 | columnName = columnName.toLowerCase();//兼容使用大写的表名 139 | boolean flag = false; 140 | for (int i = 0; i < columnName.length(); i++) { 141 | char ch = columnName.charAt(i); 142 | if ("_".charAt(0) == ch) { 143 | flag = true; 144 | } else { 145 | if (flag) { 146 | result.append(Character.toUpperCase(ch)); 147 | flag = false; 148 | } else { 149 | result.append(ch); 150 | } 151 | } 152 | } 153 | } 154 | return result.toString(); 155 | } 156 | 157 | /** 158 | * 将数据库属性名改为驼峰式,首字母大写 159 | * 160 | * @param columnName 列名 161 | * @return 162 | */ 163 | private static String columnNameConvertUpperCamel(String columnName) { 164 | String camel = columnNameConvertLowerCamel(columnName); 165 | return camel.substring(0, 1).toUpperCase() + camel.substring(1); 166 | } 167 | 168 | 169 | public boolean getIsKey() { 170 | return isKey; 171 | } 172 | 173 | public String getTypeNameUpper() { 174 | typeNameUpper = typeName.toUpperCase(); 175 | switch (typeNameUpper){ 176 | case "INT": 177 | typeNameUpper = "INTEGER"; 178 | break; 179 | case "DATETIME": 180 | typeNameUpper = "TIMESTAMP"; 181 | break; 182 | case "SMALLINT UNSIGNED": 183 | typeNameUpper = "SMALLINT"; 184 | break; 185 | case "TEXT": 186 | typeNameUpper = "LONGVARCHAR"; 187 | break; 188 | case "YEAR": 189 | typeNameUpper = "DATE"; 190 | break; 191 | case "TINYINT UNSIGNED": 192 | typeNameUpper = "TINYINT"; 193 | break; 194 | case "ENUM": 195 | typeNameUpper = "CHAR"; 196 | break; 197 | case "SET": 198 | typeNameUpper = "CHAR"; 199 | break; 200 | } 201 | return typeNameUpper; 202 | } 203 | 204 | /** 205 | * 复制属性 206 | * 207 | * @param rs 208 | * @throws SQLException 209 | */ 210 | public void copyColumnFromSqlResult(ResultSet rs) throws SQLException { 211 | try { 212 | String colName = rs.getString("COLUMN_NAME");//列名 213 | String typeName = rs.getString("TYPE_NAME");//类型名称 214 | String remarks = rs.getString("REMARKS"); 215 | int precision = rs.getInt("COLUMN_SIZE");//精度 216 | int isNull = rs.getInt("NULLABLE");//是否为空 217 | int dataType = rs.getInt("DATA_TYPE");//类型 218 | int scale = rs.getInt("DECIMAL_DIGITS");// 小数的位数 219 | 220 | this.setColName(colName); 221 | this.setTypeName(typeName); 222 | this.setPrecision(precision); 223 | this.setIsNull(isNull); 224 | this.setDataType(dataType); 225 | this.setScale(scale); 226 | this.setRemarks(StringUtils.isEmpty(remarks)?colName:remarks); 227 | } catch (SQLException e) { 228 | throw e; 229 | } 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/model/DbModel.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.model; 2 | 3 | /** 4 | * Created by lcy on 17/7/4. 5 | * 6 | * 数据库模型 7 | */ 8 | public enum DbModel { 9 | 10 | MYSQL("1"),SQLSERVER("2"),ORACLE("3"); 11 | 12 | private String type; 13 | 14 | public String getType() { 15 | return type; 16 | } 17 | 18 | public void setType(String type) { 19 | this.type = type; 20 | } 21 | 22 | DbModel(String type) { 23 | this.type = type; 24 | } 25 | 26 | DbModel() { 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/model/DbTableModel.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | import java.util.List; 7 | 8 | /** 9 | * Created by lcy on 17/7/5. 10 | * 表模型 11 | */ 12 | @Data 13 | public class DbTableModel implements Serializable{ 14 | private static final long serialVersionUID = 1803273420552584045L; 15 | 16 | public DbTableModel() { 17 | } 18 | private List columnModels; 19 | 20 | private String tableName; //表名 全小写 21 | 22 | private String entityName; 23 | 24 | private String remarks; 25 | 26 | private String mappingPath; 27 | 28 | public String getEntityName() { 29 | StringBuffer simpleEntity = new StringBuffer(); 30 | boolean upPower = true; 31 | for(int i = 0 ; i < tableName.length() ; i++){ 32 | char tab = tableName.charAt(i); 33 | String tabStr = tab + ""; 34 | //非数字 字符 35 | if(!tabStr.matches("[0-9a-zA-Z]*")){ 36 | upPower = true; 37 | continue; 38 | } 39 | if(upPower) 40 | simpleEntity.append(Character.toUpperCase(tab)); 41 | else 42 | simpleEntity.append(tab); 43 | upPower = false; 44 | } 45 | return simpleEntity.toString(); 46 | } 47 | 48 | 49 | public String getMappingPath() { 50 | return tableNameConvertMappingPath(tableName); 51 | } 52 | 53 | 54 | private static String tableNameConvertMappingPath(String tableName) { 55 | tableName = tableName.toLowerCase();//兼容使用大写的表名 56 | return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/model/ProjectConstant.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.model; 2 | 3 | /** 4 | * 项目常量 5 | */ 6 | public final class ProjectConstant { 7 | public static final String BASE_PACKAGE = "com.gwf.family.business.core";//项目基础包名称,根据自己公司的项目修改 8 | 9 | public static final String ENTITY_PACKAGE = ".entity";//Model所在包 10 | public static final String MAPPER_PACKAGE = ".dao";//Mapper所在包 11 | public static final String MAPPER_SOURCE_PACKAGE = ".mapper";//Mapper所在包 12 | public static final String SERVICE_PACKAGE = ".service";//Service所在包 13 | public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";//ServiceImpl所在包 14 | public static final String CONTROLLER_PACKAGE = ".controller";//Controller所在包 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/ApplicationContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | @Component 9 | public class ApplicationContextHolder implements ApplicationContextAware { 10 | private static ApplicationContext applicationContext; 11 | 12 | @Override 13 | public void setApplicationContext(ApplicationContext ctx) throws BeansException { 14 | applicationContext = ctx; 15 | } 16 | 17 | /** 18 | * Get application context from everywhere 19 | * 20 | * @return 21 | */ 22 | public static ApplicationContext getApplicationContext() { 23 | return applicationContext; 24 | } 25 | 26 | /** 27 | * Get bean by class 28 | * 29 | * @param clazz 30 | * @param 31 | * @return 32 | */ 33 | public static T getBean(Class clazz) { 34 | return applicationContext.getBean(clazz); 35 | } 36 | 37 | /** 38 | * Get bean by class name 39 | * 40 | * @param name 41 | * @param 42 | * @return 43 | */ 44 | @SuppressWarnings("unchecked") 45 | public static T getBean(String name) { 46 | return (T) applicationContext.getBean(name); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/CookieUtil.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import javax.servlet.http.Cookie; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | /** 7 | * cookie工具类 8 | * Created by gaowenfeng on 2017/8/2. 9 | */ 10 | public class CookieUtil { 11 | 12 | public static void set(HttpServletResponse response, 13 | String name, 14 | String value, 15 | int maxAge){ 16 | Cookie cookie = new Cookie(name,value); 17 | cookie.setPath("/"); 18 | cookie.setMaxAge(7200); 19 | response.addCookie(cookie); 20 | } 21 | 22 | public static void get(){ 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/DateUtil.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | /** 7 | * Created by lcy on 17/2/17. 8 | */ 9 | public class DateUtil { 10 | /** 11 | * 获取格式化日期 12 | * @param format 13 | * @param date 14 | * @return 15 | */ 16 | public static String getSimepleDate(String format, Date date){ 17 | if(date == null) 18 | date = new Date(); 19 | SimpleDateFormat dateFormat = new SimpleDateFormat(format); 20 | return dateFormat.format(date); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/IdGen.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import java.security.SecureRandom; 4 | import java.util.UUID; 5 | 6 | 7 | /** 8 | * Created with family. 9 | * author: cy 10 | * Date: 16/6/2 11 | * Time: 上午9:27 12 | * description: 13 | */ 14 | public class IdGen { 15 | private static SecureRandom random = new SecureRandom(); 16 | 17 | /** 18 | * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割. 19 | */ 20 | public static String uuid() { 21 | return UUID.randomUUID().toString().replaceAll("-", ""); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/JwtUtil.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import com.gwf.family.business.core.components.JwtBean; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.Jwts; 6 | import io.jsonwebtoken.SignatureAlgorithm; 7 | import lombok.Data; 8 | import org.apache.commons.collections.map.HashedMap; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.util.Date; 15 | import java.util.LinkedHashMap; 16 | import java.util.Map; 17 | 18 | /** 19 | * Created by gaowenfeng on 2017/8/9. 20 | */ 21 | @Component 22 | public class JwtUtil { 23 | private static JwtBean jwtBean; 24 | 25 | @Autowired 26 | private JwtUtil(JwtBean jwtBean){ 27 | this.jwtBean = jwtBean; 28 | } 29 | 30 | 31 | /** 32 | * 根据token获取用户名 33 | */ 34 | public static String getUsernameFromToken(String token){ 35 | try { 36 | Claims claims = jwtBean.getClaimsFromToken(token); 37 | String username = claims.getSubject(); 38 | return username; 39 | }catch (Exception e){ 40 | return null; 41 | } 42 | } 43 | 44 | /** 45 | * 设置用户信息进jwt 46 | */ 47 | public static String generateToken(UserDetails userDetails){ 48 | Map map = new HashedMap(); 49 | map.put(userDetails.getUsername(),userDetails); 50 | String token = jwtBean.generateToken(userDetails.getUsername(),map); 51 | return token; 52 | } 53 | 54 | /** 55 | * 验证token是否正确 56 | * @param token 57 | * @param userDetails 58 | * @return 59 | */ 60 | public static boolean validateToken(String token,UserDetails userDetails){ 61 | Claims claims = jwtBean.getClaimsFromToken(token); 62 | LinkedHashMap tokenUserDetails = (LinkedHashMap) claims.get(userDetails.getUsername()); 63 | boolean usernameValid = userDetails.getUsername().equals(tokenUserDetails.get("username")); 64 | boolean passwordValid = userDetails.getPassword().equals(tokenUserDetails.get("password")); 65 | if(usernameValid||passwordValid) 66 | return true; 67 | else 68 | return false; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/KeyUtil.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * Created by gaowenfeng on 2017/7/15. 7 | */ 8 | public class KeyUtil { 9 | 10 | /** 11 | * 生成唯一的主键 12 | * 格式:时间+随机数 13 | * @return 14 | */ 15 | public static synchronized String genUniqueKey(){ 16 | Random random = new Random(); 17 | Integer number = random.nextInt(900000)+100000; 18 | 19 | return System.currentTimeMillis()+String.valueOf(number); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/common/util/MathUtil.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.common.util; 2 | 3 | /** 4 | * Created by gaowenfeng on 2017/7/22. 5 | */ 6 | public class MathUtil { 7 | 8 | private static final Double Money_Range = 0.01; 9 | 10 | /** 11 | * 比较2个金额是否相等 12 | * @param d1 13 | * @param d2 14 | * @return 15 | */ 16 | public static Boolean equals(Double d1,Double d2){ 17 | Double result = Math.abs(d1 - d2); 18 | if(result{ 17 | @Override 18 | public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { 19 | jsonGenerator.writeNumber(date.getTime()/1000); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/ControllerExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | import com.gwf.family.business.core.exception.ServiceException; 4 | import com.gwf.family.business.core.results.AuthErrorEnum; 5 | import com.gwf.family.business.core.results.Result; 6 | import com.gwf.family.business.core.results.ResultCode; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.security.access.AccessDeniedException; 10 | import org.springframework.security.authentication.BadCredentialsException; 11 | import org.springframework.security.core.AuthenticationException; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.bind.annotation.ExceptionHandler; 14 | import org.springframework.web.bind.annotation.ResponseBody; 15 | import org.springframework.web.bind.annotation.ResponseStatus; 16 | import org.springframework.web.servlet.NoHandlerFoundException; 17 | 18 | /** 19 | * Created by gaowenfeng on 2017/10/3. 20 | */ 21 | @ControllerAdvice 22 | @Slf4j 23 | public class ControllerExceptionHandler { 24 | 25 | @ExceptionHandler(ServiceException.class) 26 | @ResponseBody 27 | @ResponseStatus(HttpStatus.BAD_REQUEST) 28 | public Result handleServiceException(ServiceException e){ 29 | Result result = new Result(); 30 | result.setCode(ResultCode.FAIL).setMessage(e.getMessage()); 31 | return result; 32 | } 33 | 34 | @ExceptionHandler(AuthenticationException.class) 35 | @ResponseBody 36 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 37 | public Result handleAuthenticationException(AuthenticationException e){ 38 | Result result = new Result(); 39 | if (e instanceof BadCredentialsException) 40 | result.setCode(ResultCode.UNAUTHORIZED).setMessage(AuthErrorEnum.LOGIN_PARAM_ERROR.getMessage()); 41 | else 42 | result.setCode(ResultCode.UNAUTHORIZED).setMessage(e.getMessage()); 43 | return result; 44 | } 45 | 46 | @ExceptionHandler(AccessDeniedException.class) 47 | @ResponseBody 48 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 49 | public Result handleAccessDeniedException(AccessDeniedException e){ 50 | Result result = new Result(); 51 | result.setCode(ResultCode.UNAUTHORIZED).setMessage(AuthErrorEnum.ACCESS_DENIED.getMessage()); 52 | return result; 53 | } 54 | 55 | @ExceptionHandler(NoHandlerFoundException.class) 56 | @ResponseBody 57 | @ResponseStatus(HttpStatus.NOT_FOUND) 58 | public Result handleNoHandlerFoundException(NoHandlerFoundException e){ 59 | Result result = new Result(); 60 | result.setCode(ResultCode.NOT_FOUND).setMessage("接口不存在"); 61 | return result; 62 | } 63 | 64 | @ExceptionHandler(Exception.class) 65 | @ResponseBody() 66 | @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 67 | public Result handleOtherException(Exception e){ 68 | Result result = new Result(); 69 | result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口内部错误,请联系管理员"); 70 | log.error(e.getMessage()); 71 | return result; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/FreemarkerConfig.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | import freemarker.template.TemplateExceptionHandler; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | 10 | /** 11 | * Created by gaowenfeng on 2017/7/12. 12 | */ 13 | @Configuration 14 | public class FreemarkerConfig { 15 | 16 | private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径 17 | private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/main/resources/codeftl";//模板位置 18 | //private static final String TEMPLATE_FILE_PATH = "classpath:codeftl";//模板位置 19 | 20 | @Bean 21 | private static freemarker.template.Configuration freemarkerConfiguration() throws IOException { 22 | freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23); 23 | cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH)); 24 | cfg.setDefaultEncoding("UTF-8"); 25 | cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); 26 | return cfg; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/JwtAuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | import com.gwf.family.business.core.exception.ServiceException; 4 | import com.gwf.family.business.core.results.ResultEnum; 5 | import com.gwf.family.common.util.JwtUtil; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 14 | import org.springframework.stereotype.Component; 15 | import org.springframework.web.filter.OncePerRequestFilter; 16 | 17 | import javax.servlet.FilterChain; 18 | import javax.servlet.ServletException; 19 | import javax.servlet.http.HttpServletRequest; 20 | import javax.servlet.http.HttpServletResponse; 21 | import java.io.IOException; 22 | 23 | /** 24 | * Created by gaowenfeng on 2017/8/9. 25 | */ 26 | @Slf4j 27 | public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { 28 | /** 29 | * 这里注入的是前面写的UserDetailsService的实现类 30 | */ 31 | @Autowired 32 | private UserDetailsService customUserService; 33 | 34 | @Value("${jwt.header}") 35 | private String tokenHeader; 36 | 37 | @Value("${jwt.tokenHead}") 38 | private String tokenHead; 39 | 40 | 41 | @Override 42 | protected void doFilterInternal(HttpServletRequest request, 43 | HttpServletResponse response, 44 | FilterChain chain) 45 | throws ServletException, IOException { 46 | response.setHeader("Access-Control-Allow-Origin", "*"); 47 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT"); 48 | response.setHeader("Access-Control-Allow-Headers","Authorization,Origin,X-Requested-With,X-File-Name,Content-Type, Accept"); 49 | String authHeader = request.getHeader(this.tokenHeader); // 取得header 50 | if (authHeader != null && authHeader.startsWith(tokenHead)) { //判断header头 51 | final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer " 52 | String username = JwtUtil.getUsernameFromToken(authToken); //从jwt中获取信息,如果要缓存很多信息可以用Claims 53 | logger.info("checking authentication " + username); 54 | 55 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 56 | 57 | UserDetails userDetails = this.customUserService.loadUserByUsername(username); //验证jwt的信息是否正确 58 | 59 | if (JwtUtil.validateToken(authToken, userDetails)) { 60 | //将验证信息放入SecurityContextHolder中,UsernamePasswordAuthenticationToken是Security验证账号密码的工具类 61 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( 62 | userDetails, null, userDetails.getAuthorities()); 63 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails( 64 | request)); 65 | logger.info("authenticated user " + username + ", setting security context"); 66 | SecurityContextHolder.getContext().setAuthentication(authentication); 67 | } 68 | } 69 | } 70 | 71 | chain.doFilter(request, response); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/RestAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | import com.gwf.family.business.core.results.AuthErrorEnum; 4 | import com.gwf.family.business.core.results.Result; 5 | import com.gwf.family.business.core.results.ResultCode; 6 | import org.springframework.security.core.AuthenticationException; 7 | import org.springframework.security.web.AuthenticationEntryPoint; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | 14 | /** 15 | * 实现AuthenticationEntryPoint的commence方法自定义校验不通过的方法 16 | * Created by gaowenfeng on 2017/8/9. 17 | */ 18 | public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { 19 | @Override 20 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { 21 | // 捕获AuthenticationException中的message,并封装成自定义异常抛出 22 | response.setCharacterEncoding("utf-8"); 23 | response.getWriter().write( new Result().setCode(ResultCode.UNAUTHORIZED).setMessage(AuthErrorEnum.AUTH_HEADER_ERROR.getMessage()).toString()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/WebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | 4 | import com.alibaba.fastjson.JSON; 5 | import com.alibaba.fastjson.serializer.SerializerFeature; 6 | import com.alibaba.fastjson.support.config.FastJsonConfig; 7 | import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4; 8 | import com.gwf.family.business.core.results.AuthErrorEnum; 9 | import com.gwf.family.business.core.results.Result; 10 | import com.gwf.family.business.core.results.ResultCode; 11 | import com.gwf.family.business.core.exception.ServiceException; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.apache.commons.codec.digest.DigestUtils; 14 | import org.apache.commons.lang3.StringUtils; 15 | import org.springframework.beans.factory.annotation.Value; 16 | import org.springframework.context.annotation.Configuration; 17 | import org.springframework.http.converter.HttpMessageConverter; 18 | import org.springframework.security.access.AccessDeniedException; 19 | import org.springframework.security.authentication.BadCredentialsException; 20 | import org.springframework.security.core.AuthenticationException; 21 | import org.springframework.web.method.HandlerMethod; 22 | import org.springframework.web.servlet.HandlerExceptionResolver; 23 | import org.springframework.web.servlet.ModelAndView; 24 | import org.springframework.web.servlet.NoHandlerFoundException; 25 | import org.springframework.web.servlet.config.annotation.*; 26 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 27 | 28 | import javax.servlet.http.HttpServletRequest; 29 | import javax.servlet.http.HttpServletResponse; 30 | import java.io.IOException; 31 | import java.nio.charset.Charset; 32 | import java.util.ArrayList; 33 | import java.util.Collections; 34 | import java.util.List; 35 | 36 | /** 37 | * Spring MVC 配置 38 | */ 39 | @Configuration 40 | @Slf4j 41 | public class WebMvcConfigurer extends WebMvcConfigurerAdapter { 42 | 43 | @Value("${spring.profiles.active}") 44 | private String env;//当前激活的配置文件 45 | 46 | @Override 47 | public void addViewControllers(ViewControllerRegistry registry) { 48 | registry.addViewController("/").setViewName("/connect"); 49 | } 50 | 51 | @Override 52 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 53 | registry.addResourceHandler("/static/**") 54 | .addResourceLocations("classpath:/static/"); 55 | registry.addResourceHandler("swagger-ui.html") 56 | .addResourceLocations("classpath:/META-INF/resources/"); 57 | registry.addResourceHandler("/webjars/**") 58 | .addResourceLocations("classpath:/META-INF/resources/webjars/"); 59 | super.addResourceHandlers(registry); 60 | } 61 | 62 | //使用阿里 FastJson 作为JSON MessageConverter 63 | // @Override 64 | // public void configureMessageConverters(List> converters) { 65 | // FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4(); 66 | // FastJsonConfig config = new FastJsonConfig(); 67 | // config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段 68 | // SerializerFeature.WriteNullStringAsEmpty,//String null -> "" 69 | // SerializerFeature.WriteNullNumberAsZero);//Number null -> 0 70 | // converter.setFastJsonConfig(config); 71 | // converter.setDefaultCharset(Charset.forName("UTF-8")); 72 | // converters.add(converter); 73 | // } 74 | 75 | 76 | //统一异常处理 77 | // @Override 78 | // public void configureHandlerExceptionResolvers(List exceptionResolvers) { 79 | // exceptionResolvers.add((HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) -> { 80 | // Result result = new Result(); 81 | // if (handler instanceof HandlerMethod) { 82 | // HandlerMethod handlerMethod = (HandlerMethod) handler; 83 | // if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误” 84 | // result.setCode(ResultCode.UNAUTHORIZED).setMessage(e.getMessage()); 85 | // log.info(e.getMessage()); 86 | // } else if (e instanceof AuthenticationException) { 87 | // if (e instanceof BadCredentialsException) 88 | // result.setCode(ResultCode.UNAUTHORIZED).setMessage(AuthErrorEnum.LOGIN_PARAM_ERROR.getMessage()); 89 | // else 90 | // result.setCode(ResultCode.UNAUTHORIZED).setMessage(e.getMessage()); 91 | // } else if (e instanceof AccessDeniedException) { 92 | // log.info(e.getMessage()); 93 | // result.setCode(ResultCode.UNAUTHORIZED).setMessage(AuthErrorEnum.ACCESS_DENIED.getMessage()); 94 | // } else { 95 | // result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员"); 96 | // String message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s", 97 | // request.getRequestURI(), 98 | // handlerMethod.getBean().getClass().getName(), 99 | // handlerMethod.getMethod().getName(), 100 | // e.getMessage()); 101 | // log.error(message, e); 102 | // } 103 | // } else { 104 | // if (e instanceof NoHandlerFoundException) { 105 | // result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在"); 106 | // } else { 107 | // result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage(e.getMessage()); 108 | // log.error(e.getMessage(), e); 109 | // } 110 | // } 111 | // responseResult(response, result); 112 | // return new ModelAndView(); 113 | // } 114 | // ); 115 | // } 116 | 117 | // //解决跨域问题 118 | // @Override 119 | // public void addCorsMappings(CorsRegistry registry) { 120 | // registry.addMapping("/**"); 121 | // } 122 | 123 | 124 | //添加拦截器 125 | @Override 126 | public void addInterceptors(InterceptorRegistry registry) { 127 | //接口签名认证拦截器,该签名认证比较简单,实际项目中建议使用Json Web Token代替。 128 | if (!StringUtils.contains(env, "dev")) { //开发环境忽略签名认证 129 | registry.addInterceptor(new HandlerInterceptorAdapter() { 130 | 131 | @Override 132 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 133 | String sign = request.getParameter("sign"); 134 | //验证签名 135 | if (StringUtils.isNotEmpty(sign) && validateSign(request, sign)) { 136 | return true; 137 | } else { 138 | log.warn("签名认证失败,请求接口:{},请求IP:{},请求参数:{}", 139 | request.getRequestURI(), getIpAddress(request), JSON.toJSONString(request.getParameterMap())); 140 | 141 | Result result = new Result(); 142 | result.setCode(ResultCode.UNAUTHORIZED).setMessage("签名认证失败"); 143 | responseResult(response, result); 144 | return false; 145 | } 146 | } 147 | }); 148 | } 149 | } 150 | 151 | 152 | 153 | private void responseResult(HttpServletResponse response, Result result) { 154 | response.setCharacterEncoding("UTF-8"); 155 | response.setHeader("Content-type", "application/json;charset=UTF-8"); 156 | response.setStatus(result.getCode()); 157 | try { 158 | response.getWriter().write(JSON.toJSONString(result)); 159 | } catch (IOException ex) { 160 | log.error(ex.getMessage()); 161 | } 162 | } 163 | 164 | /** 165 | * 一个简单的签名认证,规则:请求参数按ASCII码排序后,拼接为a=value&b=value...这样的字符串后进行MD5 166 | * 167 | * @param request 168 | * @param requestSign 169 | * @return 170 | */ 171 | private boolean validateSign(HttpServletRequest request, String requestSign) { 172 | List keys = new ArrayList(request.getParameterMap().keySet()); 173 | Collections.sort(keys); 174 | 175 | String linkString = ""; 176 | 177 | for (String key : keys) { 178 | if (!"sign".equals(key)) { 179 | linkString += key + "=" + request.getParameter(key) + "&"; 180 | } 181 | } 182 | if (StringUtils.isEmpty(linkString)) 183 | return false; 184 | 185 | linkString = linkString.substring(0, linkString.length() - 1); 186 | String key = "Potato";//自己修改 187 | String sign = DigestUtils.md5Hex(linkString + key); 188 | 189 | return StringUtils.equals(sign, requestSign); 190 | 191 | } 192 | 193 | private String getIpAddress(HttpServletRequest request) { 194 | String ip = request.getHeader("x-forwarded-for"); 195 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 196 | ip = request.getHeader("Proxy-Client-IP"); 197 | } 198 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 199 | ip = request.getHeader("WL-Proxy-Client-IP"); 200 | } 201 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 202 | ip = request.getHeader("HTTP_CLIENT_IP"); 203 | } 204 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 205 | ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 206 | } 207 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 208 | ip = request.getRemoteAddr(); 209 | } 210 | // 如果是多级代理,那么取第一个ip为客户ip 211 | if (ip != null && ip.indexOf(",") != -1) { 212 | ip = ip.substring(0, ip.indexOf(",")).trim(); 213 | } 214 | 215 | return ip; 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/configurer/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.configurer; 2 | 3 | import com.gwf.family.business.core.components.JwtBean; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.security.crypto.password.PasswordEncoder; 16 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 17 | 18 | /** 19 | * Created by gaowenfeng on 2017/8/9. 20 | */ 21 | @Configuration 22 | @EnableWebSecurity //开启WebSecurity支持 23 | @EnableGlobalMethodSecurity(prePostEnabled = true) //开启prePostEnabled注解支持 24 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 25 | 26 | @Autowired 27 | private UserDetailsService jwtUserDetailsServiceImpl; 28 | 29 | @Override 30 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 31 | auth 32 | .userDetailsService(jwtUserDetailsServiceImpl) 33 | .passwordEncoder(passwordEncoder()); 34 | } 35 | 36 | /** 37 | * 密码加密的bean,使用BCrypt 38 | * @return 39 | */ 40 | @Bean 41 | public PasswordEncoder passwordEncoder() { 42 | return new BCryptPasswordEncoder(); 43 | } 44 | 45 | /** 46 | * 前置过滤器 47 | * @return 48 | */ 49 | @Bean 50 | JwtAuthenticationTokenFilter authenticationTokenFilterBean(){ 51 | return new JwtAuthenticationTokenFilter(); 52 | } 53 | 54 | @Bean 55 | JwtBean jwtBean(){ 56 | return new JwtBean(); 57 | } 58 | 59 | @Override 60 | protected void configure(HttpSecurity http) throws Exception { 61 | http 62 | .csrf() 63 | .disable() //禁用csrf保护 64 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //禁用session 65 | .and() 66 | .authorizeRequests() //所有请求都要验证 67 | .antMatchers("/static/**").permitAll() //静态资源过滤 68 | .antMatchers("/webjars/**").permitAll() //swagger过滤 69 | .antMatchers("/v2/**").permitAll() //swagger过滤 70 | .antMatchers("/swagger-resources/**").permitAll() //swagger过滤 71 | .antMatchers("/swagger-resources/**").permitAll() //swagger过滤 72 | .antMatchers("/auth/**").permitAll() //登录注册等请求过滤 73 | .antMatchers("/code/**").permitAll() //下载代码请求过滤 74 | .antMatchers("/favicon.ico","/swagger-ui.html","/").permitAll() 75 | .anyRequest().fullyAuthenticated() 76 | .and() 77 | .exceptionHandling() //验证不通过的配置 78 | .authenticationEntryPoint(new RestAuthenticationEntryPoint()) 79 | ; 80 | http //添加前置过滤器 81 | .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 82 | http //禁用header缓存 83 | .headers().cacheControl(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/role/controller/SysRoleController.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.role.controller; 2 | import com.gwf.family.business.core.results.Result; 3 | import com.gwf.family.business.core.results.ResultGenerator; 4 | import com.gwf.family.sys.role.entity.SysRole; 5 | import com.gwf.family.sys.role.service.SysRoleService; 6 | import com.github.pagehelper.PageHelper; 7 | import com.github.pagehelper.PageInfo; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import javax.validation.Valid; 12 | import java.util.List; 13 | 14 | /** 15 | * Created by gwf on 2017-8-10 14:15:19. 16 | */ 17 | @RestController 18 | @RequestMapping("/sys/role") 19 | public class SysRoleController { 20 | @Autowired 21 | private SysRoleService sysRoleService; 22 | 23 | @PostMapping 24 | public Result add(SysRole sysRole) { 25 | sysRoleService.save(sysRole); 26 | return ResultGenerator.genSuccessResult(); 27 | } 28 | 29 | @DeleteMapping("/{id:\\d+}") 30 | public Result delete(@PathVariable Integer id) { 31 | sysRoleService.deleteById(id); 32 | return ResultGenerator.genSuccessResult(); 33 | } 34 | 35 | @PutMapping("/{id:\\d+}") 36 | public Result update(SysRole sysRole) { 37 | sysRoleService.update(sysRole); 38 | return ResultGenerator.genSuccessResult(); 39 | } 40 | 41 | @GetMapping("/{id:\\d+}") 42 | public Result detail(@PathVariable Integer id) { 43 | SysRole sysRole = sysRoleService.findById(id); 44 | return ResultGenerator.genSuccessResult(sysRole); 45 | } 46 | 47 | @GetMapping 48 | public Result list(@RequestParam(name = "page",defaultValue = "1") Integer page, 49 | @RequestParam(name = "size",defaultValue = "10") Integer size) { 50 | PageHelper.startPage(page, size); 51 | List list = sysRoleService.findAll(); 52 | PageInfo pageInfo = new PageInfo(list); 53 | return ResultGenerator.genSuccessResult(pageInfo); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/role/dao/SysRoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.role.dao; 2 | 3 | import com.gwf.family.business.core.mapper.Mapper; 4 | import com.gwf.family.sys.role.entity.SysRole; 5 | import org.apache.ibatis.annotations.Select; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Created with gwf on 2017-8-10 14:15:19. 11 | */ 12 | @org.apache.ibatis.annotations.Mapper 13 | public interface SysRoleRepository extends Mapper { 14 | @Select("select t2.* from sys_user_roles t1 left join sys_role t2 on t1.role_id = t2.id where user_id = #{user_id}") 15 | List findRolesByUserId(Integer userId); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/role/entity/SysRole.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.role.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created with gwf on 2017-8-10 14:15:19. 10 | */ 11 | @Entity 12 | @Data 13 | @Table(name = "sys_role") 14 | public class SysRole implements Serializable{ 15 | private static final long serialVersionUID = 3433359804434539319L; 16 | 17 | public SysRole(){ 18 | } 19 | 20 | public SysRole(Integer id,String name){ 21 | this.id=id; 22 | this.name=name; 23 | } 24 | 25 | /** id */ 26 | @Id 27 | private Integer id; 28 | /** name */ 29 | private String name; 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/role/service/SysRoleService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.role.service; 2 | import com.gwf.family.sys.role.entity.SysRole; 3 | import com.gwf.family.business.core.service.Service; 4 | 5 | 6 | /** 7 | * Created by gwf on 2017-8-10 14:15:19. 8 | */ 9 | public interface SysRoleService extends Service { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/role/service/impl/SysRoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.role.service.impl; 2 | 3 | import com.gwf.family.sys.role.dao.SysRoleRepository; 4 | import com.gwf.family.sys.role.entity.SysRole; 5 | import com.gwf.family.sys.role.service.SysRoleService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import com.gwf.family.business.core.service.AbstractService; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | 12 | 13 | /** 14 | * Created by gwf on 2017-8-10 14:15:19. 15 | */ 16 | @Service 17 | @Transactional 18 | public class SysRoleServiceImpl extends AbstractService implements SysRoleService { 19 | @Autowired 20 | private SysRoleRepository sysRoleRepository; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/user/controller/SysUserController.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.user.controller; 2 | import com.gwf.family.business.core.exception.ServiceException; 3 | import com.gwf.family.business.core.results.Result; 4 | import com.gwf.family.business.core.results.ResultEnum; 5 | import com.gwf.family.business.core.results.ResultGenerator; 6 | import com.gwf.family.sys.user.entity.SysUser; 7 | import com.gwf.family.sys.user.service.SysUserService; 8 | import com.github.pagehelper.PageHelper; 9 | import com.github.pagehelper.PageInfo; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.security.access.prepost.PostAuthorize; 12 | import org.springframework.security.access.prepost.PreAuthorize; 13 | import org.springframework.web.bind.annotation.*; 14 | 15 | import java.util.List; 16 | 17 | /** 18 | * Created by gwf on 2017-8-10 14:15:19. 19 | */ 20 | @RestController 21 | @RequestMapping("/sys/user") 22 | //@PreAuthorize("hasRole('ROLE_ADMIN')") 23 | public class SysUserController { 24 | @Autowired 25 | private SysUserService sysUserService; 26 | 27 | @PostMapping 28 | public Result add(SysUser sysUser) { 29 | sysUserService.save(sysUser); 30 | return ResultGenerator.genSuccessResult(); 31 | } 32 | @DeleteMapping("/{id:\\d+}") 33 | public Result delete(@PathVariable Integer id) { 34 | sysUserService.deleteById(id); 35 | return ResultGenerator.genSuccessResult(); 36 | } 37 | 38 | @PutMapping("/{id:\\d+}") 39 | public Result update(SysUser sysUser) { 40 | sysUserService.update(sysUser); 41 | return ResultGenerator.genSuccessResult(); 42 | } 43 | 44 | @PostAuthorize("returnObject.data.username == principal.username or hasRole('ROLE_ADMIN')") 45 | @GetMapping("/{id:\\d+}") 46 | public Result detail(@PathVariable Integer id) { 47 | SysUser sysUser = sysUserService.findById(id); 48 | if(sysUser==null) 49 | throw new ServiceException(ResultEnum.USER_NOT_EXISTS); 50 | return ResultGenerator.genSuccessResult(sysUser); 51 | } 52 | 53 | @GetMapping 54 | public Result list(@RequestParam(name = "page",defaultValue = "1") Integer page, 55 | @RequestParam(name = "size",defaultValue = "10") Integer size) { 56 | PageHelper.startPage(page, size); 57 | List list = sysUserService.findAll(); 58 | PageInfo pageInfo = new PageInfo(list); 59 | return ResultGenerator.genSuccessResult(pageInfo); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/user/dao/SysUserRepository.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.user.dao; 2 | 3 | import com.gwf.family.business.core.mapper.Mapper; 4 | import com.gwf.family.sys.user.entity.SysUser; 5 | import org.apache.ibatis.annotations.ResultMap; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | /** 9 | * Created with gwf on 2017-8-10 14:15:19. 10 | */ 11 | @org.apache.ibatis.annotations.Mapper 12 | public interface SysUserRepository extends Mapper { 13 | 14 | @Select("select * from sys_user where username = #{username}") 15 | @ResultMap("BaseResultMap") 16 | SysUser findByUserName(String username); 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/user/entity/SysUser.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.user.entity; 2 | 3 | import com.gwf.family.sys.role.entity.SysRole; 4 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 5 | import lombok.Data; 6 | 7 | import javax.persistence.*; 8 | import java.io.Serializable; 9 | import java.util.List; 10 | 11 | /** 12 | * Created with gwf on 2017-8-10 14:15:19. 13 | */ 14 | @Entity 15 | @Data 16 | @Table(name = "sys_user") 17 | public class SysUser implements Serializable{ 18 | private static final long serialVersionUID = 4857621004791624053L; 19 | 20 | public SysUser(){ 21 | } 22 | 23 | public SysUser(Integer id,String password,String username){ 24 | this.id=id; 25 | this.password=password; 26 | this.username=username; 27 | } 28 | 29 | /** id */ 30 | @Id 31 | private Integer id; 32 | /** 密码 */ 33 | private String password; 34 | /** 用户名 */ 35 | private String username; 36 | 37 | /**权限列表**/ 38 | @Transient 39 | private List roles; 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/user/service/SysUserService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.user.service; 2 | import com.gwf.family.sys.user.entity.SysUser; 3 | import com.gwf.family.business.core.service.Service; 4 | 5 | 6 | /** 7 | * Created by gwf on 2017-8-10 14:15:19. 8 | */ 9 | public interface SysUserService extends Service { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/user/service/impl/SysUserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.user.service.impl; 2 | 3 | import com.gwf.family.sys.user.dao.SysUserRepository; 4 | import com.gwf.family.sys.user.entity.SysUser; 5 | import com.gwf.family.sys.user.service.SysUserService; 6 | import com.gwf.family.sys.userroles.dao.SysUserRolesRepository; 7 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import com.gwf.family.business.core.service.AbstractService; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.transaction.annotation.Transactional; 12 | import org.springframework.util.CollectionUtils; 13 | 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | 17 | 18 | /** 19 | * Created by gwf on 2017-8-10 14:15:19. 20 | */ 21 | @Service 22 | @Transactional 23 | public class SysUserServiceImpl extends AbstractService implements SysUserService { 24 | @Autowired 25 | private SysUserRepository sysUserRepository; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/userroles/controller/SysUserRolesController.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.userroles.controller; 2 | import com.gwf.family.business.core.results.Result; 3 | import com.gwf.family.business.core.results.ResultGenerator; 4 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 5 | import com.gwf.family.sys.userroles.service.SysUserRolesService; 6 | import com.github.pagehelper.PageHelper; 7 | import com.github.pagehelper.PageInfo; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Created by gwf on 2017-8-10 14:15:19. 15 | */ 16 | @RestController 17 | @RequestMapping("/sys/user/roles") 18 | public class SysUserRolesController { 19 | @Autowired 20 | private SysUserRolesService sysUserRolesService; 21 | 22 | @PostMapping 23 | public Result add(SysUserRoles sysUserRoles) { 24 | sysUserRolesService.save(sysUserRoles); 25 | return ResultGenerator.genSuccessResult(); 26 | } 27 | 28 | @DeleteMapping("/{id:\\d+}") 29 | public Result delete(@PathVariable Integer id) { 30 | sysUserRolesService.deleteById(id); 31 | return ResultGenerator.genSuccessResult(); 32 | } 33 | 34 | @PutMapping("/{id:\\d+}") 35 | public Result update(SysUserRoles sysUserRoles) { 36 | sysUserRolesService.update(sysUserRoles); 37 | return ResultGenerator.genSuccessResult(); 38 | } 39 | 40 | @GetMapping("/{id:\\d+}") 41 | public Result detail(@PathVariable Integer id) { 42 | SysUserRoles sysUserRoles = sysUserRolesService.findById(id); 43 | return ResultGenerator.genSuccessResult(sysUserRoles); 44 | } 45 | 46 | @GetMapping 47 | public Result list(@RequestParam(name = "page",defaultValue = "1") Integer page, 48 | @RequestParam(name = "size",defaultValue = "10") Integer size) { 49 | PageHelper.startPage(page, size); 50 | List list = sysUserRolesService.findAll(); 51 | PageInfo pageInfo = new PageInfo(list); 52 | return ResultGenerator.genSuccessResult(pageInfo); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/userroles/dao/SysUserRolesRepository.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.userroles.dao; 2 | 3 | import com.gwf.family.business.core.mapper.Mapper; 4 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 5 | 6 | /** 7 | * Created with gwf on 2017-8-10 14:15:19. 8 | */ 9 | @org.apache.ibatis.annotations.Mapper 10 | public interface SysUserRolesRepository extends Mapper { 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/userroles/entity/SysUserRoles.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.userroles.entity; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.*; 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Created with gwf on 2017-8-10 14:15:19. 10 | */ 11 | @Entity 12 | @Data 13 | @Table(name = "sys_user_roles") 14 | public class SysUserRoles implements Serializable{ 15 | private static final long serialVersionUID = 6379522951278191261L; 16 | 17 | public SysUserRoles(){ 18 | } 19 | 20 | public SysUserRoles(Integer userId, Integer roleId) { 21 | this.userId = userId; 22 | this.roleId = roleId; 23 | } 24 | 25 | @Id 26 | private Integer id; 27 | /** sys_user_id */ 28 | private Integer userId; 29 | /** roles_id */ 30 | private Integer roleId; 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/userroles/service/SysUserRolesService.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.userroles.service; 2 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 3 | import com.gwf.family.business.core.service.Service; 4 | 5 | 6 | /** 7 | * Created by gwf on 2017-8-10 14:15:19. 8 | */ 9 | public interface SysUserRolesService extends Service { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/gwf/family/sys/userroles/service/impl/SysUserRolesServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.sys.userroles.service.impl; 2 | 3 | import com.gwf.family.sys.userroles.dao.SysUserRolesRepository; 4 | import com.gwf.family.sys.userroles.entity.SysUserRoles; 5 | import com.gwf.family.sys.userroles.service.SysUserRolesService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import com.gwf.family.business.core.service.AbstractService; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | 12 | 13 | /** 14 | * Created by gwf on 2017-8-10 14:15:19. 15 | */ 16 | @Service 17 | @Transactional 18 | public class SysUserRolesServiceImpl extends AbstractService implements SysUserRolesService { 19 | @Autowired 20 | private SysUserRolesRepository sysUserRolesRepository; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | # 数据库配置 3 | redis: 4 | # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突 5 | database: 3 6 | # redis服务器地址(默认为localhost) 7 | host: localhost 8 | # redis端口(默认为6379) 9 | port: 6379 10 | # redis访问密码(默认为空) 11 | password: 12 | # redis连接超时时间(单位为毫秒) 13 | timeout: 0 14 | # redis连接池配置 15 | pool: 16 | # 最大可用连接数(默认为8,负数表示无限) 17 | max-active: 8 18 | # 最大空闲连接数(默认为8,负数表示无限) 19 | max-idle: 8 20 | # 最小空闲连接数(默认为0,该值只有为正数才有作用) 21 | min-idle: 0 22 | # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限) 23 | max-wait: -1 24 | jackson: 25 | default-property-inclusion: non_null 26 | datasource: 27 | driver-class-name: org.gjt.mm.mysql.Driver 28 | url: jdbc:mysql://localhost:3306/gwf?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=true 29 | username: root 30 | password: root 31 | 32 | # 服务器配置 33 | server: 34 | port: 9999 35 | context-path: / 36 | 37 | # mybatis配置 38 | mybatis: 39 | # 配置映射类所在包名 40 | # type-aliases-package: com.gwf.family.business.domain 41 | # 配置mapper xml文件所在路径,这里是一个数组 42 | mapper-locations: 43 | - mappers/**/*.xml 44 | 45 | mapper: 46 | mappers: 47 | - com.gwf.family.business.core.mapper.Mapper 48 | not-empty: false 49 | identity: MYSQL 50 | 51 | pagehelper: 52 | helperDialect: mysql 53 | reasonable: true 54 | supportMethodsArguments: true 55 | params: count=countSql 56 | logging: 57 | level: 58 | com.gwf.family: trace 59 | 60 | jwt: 61 | header: Authorization 62 | secret: mySecret 63 | expiration: 604800 64 | tokenHead: "Bearer " 65 | route: 66 | authentication: 67 | path: auth 68 | refresh: refresh 69 | register: "auth/register" 70 | 71 | #druid: 72 | # url: jdbc:mysql://localhost:3306/gwf?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true 73 | # username: root 74 | # password: root 75 | # initial-size: 1 76 | # min-idle: 1 77 | # max-active: 20 78 | # test-on-borrow: true 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/main/resources/application-pro.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkGao11520/spring-boot-mybatis-with-redis/b5b08d407cb15f8a488c852d63278390a31d5945/src/main/resources/application-pro.yml -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: dev 4 | mvc: 5 | throw-exception-if-no-handler-found: true 6 | resources: 7 | add-mappings: false -------------------------------------------------------------------------------- /src/main/resources/codeftl/controller.ftl: -------------------------------------------------------------------------------- 1 | package ${basePackage}.controller; 2 | import ${corePackage}.results.Result; 3 | import ${corePackage}.results.ResultGenerator; 4 | import ${basePackage}.entity.${table.entityName}; 5 | import ${basePackage}.service.${table.entityName}Service; 6 | import com.github.pagehelper.PageHelper; 7 | import com.github.pagehelper.PageInfo; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | import io.swagger.annotations.*; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * Created by ${author} on ${.now}. 16 | */ 17 | @RestController 18 | @RequestMapping("${table.mappingPath}") 19 | public class ${table.entityName}Controller { 20 | @Autowired 21 | private ${table.entityName}Service ${table.entityName?uncap_first}Service; 22 | 23 | @PostMapping 24 | @ApiOperation("添加${table.entityName}") 25 | public Result add(${table.entityName} ${table.entityName?uncap_first}) { 26 | ${table.entityName?uncap_first}Service.save(${table.entityName?uncap_first}); 27 | return ResultGenerator.genSuccessResult(); 28 | } 29 | 30 | @DeleteMapping("/{id:\\d+}") 31 | @ApiOperation("删除${table.entityName}") 32 | public Result delete(@ApiParam(value = "${table.remarks}id") @PathVariable Integer id) { 33 | ${table.entityName?uncap_first}Service.deleteById(id); 34 | return ResultGenerator.genSuccessResult(); 35 | } 36 | 37 | @PutMapping("/{id:\\d+}") 38 | @ApiOperation("修改${table.entityName}") 39 | public Result update(${table.entityName} ${table.entityName?uncap_first}) { 40 | ${table.entityName?uncap_first}Service.update(${table.entityName?uncap_first}); 41 | return ResultGenerator.genSuccessResult(); 42 | } 43 | 44 | @GetMapping("/{id:\\d+}") 45 | @ApiOperation("${table.entityName}根据id查询详情") 46 | public Result detail(@ApiParam(value = "${table.remarks}id")@PathVariable Integer id) { 47 | ${table.entityName} ${table.entityName?uncap_first} = ${table.entityName?uncap_first}Service.findById(id); 48 | return ResultGenerator.genSuccessResult(${table.entityName?uncap_first}); 49 | } 50 | 51 | @GetMapping 52 | @ApiOperation("${table.entityName}分页查询列表") 53 | public Result list(@ApiParam(value = "页数")@RequestParam(name = "page",defaultValue = "1") Integer page, 54 | @ApiParam(value = "每页行数")@RequestParam(name = "size",defaultValue = "10") Integer size) { 55 | PageHelper.startPage(page, size); 56 | List<${table.entityName}> list = ${table.entityName?uncap_first}Service.findAll(); 57 | PageInfo pageInfo = new PageInfo(list); 58 | return ResultGenerator.genSuccessResult(pageInfo); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/resources/codeftl/entity.ftl: -------------------------------------------------------------------------------- 1 | package ${basePackage}.entity; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import lombok.AllArgsConstructor; 6 | 7 | import javax.persistence.*; 8 | import java.math.BigDecimal; 9 | import java.math.BigInteger; 10 | import java.io.Serializable; 11 | import java.util.Date; 12 | import java.util.List; 13 | import io.swagger.annotations.*; 14 | 15 | /** 16 | * Created with ${author} on ${.now}. 17 | */ 18 | @Entity 19 | @Data 20 | @Table(name = "${table.tableName}") 21 | @NoArgsConstructor 22 | @AllArgsConstructor 23 | public class ${table.entityName} implements Serializable{ 24 | 25 | <#list table.columnModels as item> 26 | /** ${item.remarks} */ 27 | <#if item.isKey> 28 | @Id 29 | 30 | @ApiModelProperty(value = "${item.remarks}") 31 | private ${item.javaType} ${item.columnNameLowerCamel}; 32 | 33 | 34 | } 35 | 36 | -------------------------------------------------------------------------------- /src/main/resources/codeftl/mapper.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <#list table.columnModels as item> 6 | <#if item.isKey> 7 | 8 | 9 | <#if !item.isKey> 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/main/resources/codeftl/repository.ftl: -------------------------------------------------------------------------------- 1 | package ${basePackage}.dao; 2 | 3 | import ${corePackage}.mapper.Mapper; 4 | import ${basePackage}.entity.${table.entityName}; 5 | 6 | /** 7 | * Created with ${author} on ${.now}. 8 | */ 9 | @org.apache.ibatis.annotations.Mapper 10 | public interface ${table.entityName}Repository extends Mapper<${table.entityName}> { 11 | 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/main/resources/codeftl/service.ftl: -------------------------------------------------------------------------------- 1 | package ${basePackage}.service; 2 | import ${basePackage}.entity.${table.entityName}; 3 | import ${corePackage}.service.Service; 4 | 5 | 6 | /** 7 | * Created by ${author} on ${.now}. 8 | */ 9 | public interface ${table.entityName}Service extends Service<${table.entityName}> { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/codeftl/serviceimpl.ftl: -------------------------------------------------------------------------------- 1 | package ${basePackage}.service.impl; 2 | 3 | import ${basePackage}.dao.${table.entityName}Repository; 4 | import ${basePackage}.entity.${table.entityName}; 5 | import ${basePackage}.service.${table.entityName}Service; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import ${corePackage}.service.AbstractService; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | 12 | 13 | /** 14 | * Created by ${author} on ${.now}. 15 | */ 16 | @Service 17 | @Transactional 18 | public class ${table.entityName}ServiceImpl extends AbstractService<${table.entityName}> implements ${table.entityName}Service { 19 | @Autowired 20 | private ${table.entityName}Repository ${table.entityName?uncap_first}Repository; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | %d - %msg%n 9 | 10 | 11 | 12 | 13 | 14 | 15 | ERROR 16 | DENY 17 | ACCEPT 18 | 19 | 20 | 21 | %msg%n 22 | 23 | 24 | 25 | 26 | 27 | /Users/gaowenfeng/documents/tomcat/sell/info.%d.log 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | ERROR 36 | 37 | 38 | 39 | %msg%n 40 | 41 | 42 | 43 | 44 | 45 | /Users/gaowenfeng/documents/sell/error.%d.log 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/main/resources/mappers/sys/role/mapper/SysRoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/resources/mappers/sys/user/mapper/SysUserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/mappers/sys/userroles/mapper/SysUserRolesMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/static/connect.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by gaowenfeng on 2017/7/13. 3 | */ 4 | function connect() { 5 | $.ajax({ 6 | type: 'post', 7 | url: './code/connectDb', 8 | data: { 9 | ip: $('#ip').val(), 10 | db: $('#db').val(), 11 | port: $('#port').val(), 12 | dbName: $('#dbName').val(), 13 | username: $('#username').val(), 14 | password: $('#password').val() 15 | }, 16 | success: function (result) { 17 | if(result.code==200){ 18 | alert("连接成功"); 19 | var str = '
'; 20 | var list = result.data; 21 | for (var i = 0; i < list.length; i++) 22 | str += (list[i].tableName+':    '); 23 | $('#tableDiv').append(str); 24 | } 25 | }, 26 | error: function (error) { 27 | alert(JSON.stringify(error)); 28 | } 29 | }) 30 | } 31 | 32 | function generate() { 33 | var str = ""; 34 | var j = 0 35 | for (var i = 0; i < document.getElementsByName('table').length; i++) { 36 | if (document.getElementsByName('table')[i].checked) { 37 | if (j == 0) 38 | str += document.getElementsByName('table')[i].value; 39 | else 40 | str += "," +document.getElementsByName('table')[i].value; 41 | j++; 42 | } 43 | } 44 | if (str == "") { 45 | alert("您没有选择任何数据"); 46 | } else { 47 | window.location.href = './code/constructCode?ip=' + $('#ip').val() + '&db=' + $('#db').val() + '&port=' + $('#port').val() + '&dbName=' + $('#dbName').val() + '&username=' + $('#username').val() + '&password=' + $('#password').val() + '&tables=' + str + '&basePackage=' + $('#basepackage').val()+'&author='+$('#author').val(); 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/resources/templates/connect.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 代码生成 4 | 5 | 6 | ip:

7 | db:

12 | port:

13 | dbName:

14 | username:

15 | password:

16 | 17 |
18 |
19 | basepackage:

20 | author:

21 |
22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/test/java/com/gwf/family/SpringBootMybatisWithRedisApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | import org.springframework.test.context.ActiveProfiles; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | @Slf4j 15 | public class SpringBootMybatisWithRedisApplicationTests { 16 | 17 | @Test 18 | public void testEncoder(){ 19 | BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); 20 | log.info(encoder.encode("123")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/gwf/family/business/core/service/JwtUserDetailServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package com.gwf.family.business.core.service; 2 | 3 | import com.gwf.family.SpringBootMybatisWithRedisApplication; 4 | import com.gwf.family.business.core.entity.JwtUser; 5 | import com.gwf.family.sys.user.entity.SysUser; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | 14 | import static org.junit.Assert.*; 15 | 16 | /** 17 | * Created by gaowenfeng on 2017/8/10. 18 | */ 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest 21 | public class JwtUserDetailServiceImplTest{ 22 | 23 | @Autowired 24 | private JwtUserDetailServiceImpl jwtUserDetailService; 25 | 26 | @Test 27 | public void loadUserByUsername() throws Exception { 28 | UserDetails jwtUser = jwtUserDetailService.loadUserByUsername("gwf"); 29 | Assert.assertNotNull(jwtUser); 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /src/test/resources/sql/data.sql: -------------------------------------------------------------------------------- 1 | BEGIN; 2 | 3 | INSERT INTO `sys_role` 4 | VALUES 5 | ('1', 'ROLE_ADMIN'), 6 | ('2', 'ROLE_USER'); 7 | 8 | INSERT INTO `sys_user` 9 | VALUES 10 | ('1', '$2a$10$NYw3YvE.XvF.hgMHfAoLo.KtMT6KpWKxNtoUhFZbM2zNuUyiJWcp2', 'gwf'), 11 | ('2', '$2a$10$NYw3YvE.XvF.hgMHfAoLo.KtMT6KpWKxNtoUhFZbM2zNuUyiJWcp2', 'jd'), 12 | ('3', '$2a$10$NYw3YvE.XvF.hgMHfAoLo.KtMT6KpWKxNtoUhFZbM2zNuUyiJWcp2', 'gzf'); 13 | 14 | INSERT INTO `sys_user_roles` 15 | VALUES 16 | ('1', '1', '1'); 17 | 18 | COMMIT; -------------------------------------------------------------------------------- /src/test/resources/sql/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `sys_user` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `password` varchar(256) COLLATE utf8_bin DEFAULT NULL, 4 | `username` varchar(256) COLLATE utf8_bin DEFAULT NULL, 5 | PRIMARY KEY (`id`) 6 | ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=utf8 COLLATE=utf8_bin 7 | 8 | CREATE TABLE `sys_role` ( 9 | `id` int(11) NOT NULL AUTO_INCREMENT, 10 | `name` varchar(256) COLLATE utf8_bin DEFAULT NULL, 11 | PRIMARY KEY (`id`) 12 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin 13 | 14 | CREATE TABLE `sys_user_roles` ( 15 | `user_id` int(11) NOT NULL, 16 | `role_id` int(11) NOT NULL, 17 | `id` int(11) NOT NULL AUTO_INCREMENT, 18 | PRIMARY KEY (`id`), 19 | KEY `FKdpvc6d7xqpqr43dfuk1s27cqh` (`role_id`), 20 | KEY `FKd0ut7sloes191bygyf7a3pk52` (`user_id`) 21 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin --------------------------------------------------------------------------------