├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── LICENSE
├── README.md
├── derby.log
├── mvnw
├── mvnw.cmd
├── pom.xml
├── simluation-project-startup.bat
├── src
├── main
│ ├── java
│ │ └── com
│ │ │ └── yizhuoyan
│ │ │ ├── core
│ │ │ ├── AjaxResponse.java
│ │ │ ├── AssertThrowUtil.java
│ │ │ ├── JsonUtil.java
│ │ │ ├── PlatformException.java
│ │ │ ├── ThisSystemUtil.java
│ │ │ └── UserContext.java
│ │ │ └── teaching
│ │ │ └── demo
│ │ │ ├── AjaxApplication.java
│ │ │ ├── controller
│ │ │ ├── AuthorizationInterceptor.java
│ │ │ ├── LogHandler.java
│ │ │ ├── NoAuthorizationHandler.java
│ │ │ ├── SimpleAjaxHandler.java
│ │ │ ├── UserHandler.java
│ │ │ └── ao
│ │ │ │ ├── ModifyPasswordAo.java
│ │ │ │ ├── UpdateUserAo.java
│ │ │ │ └── UserAo.java
│ │ │ ├── core
│ │ │ ├── AjaxResponse.java
│ │ │ ├── AssertThrowUtil.java
│ │ │ ├── EncrypDES.java
│ │ │ ├── JsonUtil.java
│ │ │ ├── PaginationQueryResult.java
│ │ │ ├── PlatformException.java
│ │ │ ├── RMBUpper.java
│ │ │ ├── ThisSystemUtil.java
│ │ │ ├── UserContext.java
│ │ │ └── config
│ │ │ │ └── MVCConfig.java
│ │ │ ├── dao
│ │ │ ├── SecurityLogDao.java
│ │ │ └── UserDao.java
│ │ │ ├── entity
│ │ │ ├── SecurityLogEntity.java
│ │ │ └── UserEntity.java
│ │ │ └── function
│ │ │ ├── LogService.java
│ │ │ ├── UserFunction.java
│ │ │ └── impl
│ │ │ ├── LogServiceImpl.java
│ │ │ └── UserFunctionImpl.java
│ └── resources
│ │ ├── application.properties
│ │ └── logback.xml
└── test
│ └── java
│ └── com
│ └── yizhuoyan
│ └── teaching
│ └── demo
│ └── AjaxApplicationTests.java
└── 模拟web项目API服务数据接口文档.docx
/.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 | .sts4-cache
12 |
13 | ### IntelliJ IDEA ###
14 | .idea
15 | *.iws
16 | *.iml
17 | *.ipr
18 |
19 | ### NetBeans ###
20 | /nbproject/private/
21 | /build/
22 | /nbbuild/
23 | /dist/
24 | /nbdist/
25 | /.nb-gradle/
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yizhuoyan/teaching-project-ajax/157ad8eb939c9ac262e9ea34fbbd31d780bea693/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # teaching-ajax
2 | the java-web project build with spring-boot for student learning the ajax technology.
3 |
--------------------------------------------------------------------------------
/derby.log:
--------------------------------------------------------------------------------
1 | ----------------------------------------------------------------
2 | Tue Apr 24 17:35:53 GMT+08:00 2018:
3 | Booting Derby version The Apache Software Foundation - Apache Derby - 10.14.1.0 - (1808820): instance a816c00e-0162-f702-6781-00000537dfc0
4 | on database directory memory:E:\Private-Project\courseware\teaching-project\testdb with class loader sun.misc.Launcher$AppClassLoader@4aa298b7
5 | Loaded from file:/D:/opt/apache-maven/apache-maven-3.5.0/local-repository/org/apache/derby/derby/10.14.1.0/derby-10.14.1.0.jar
6 | java.vendor=Oracle Corporation
7 | java.runtime.version=1.8.0_131-b11
8 | user.dir=E:\Private-Project\courseware\teaching-project
9 | os.name=Windows 7
10 | os.arch=amd64
11 | os.version=6.1
12 | derby.system.home=null
13 | Database Class Loader started - derby.database.classpath=''
14 |
--------------------------------------------------------------------------------
/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.yizhuoyan.teaching.demo
7 | simulation-project
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | ajax
12 | a simple web project for student study ajax
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.1.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 |
30 | com.fasterxml.jackson
31 | jackson-bom
32 | 2.9.2
33 | pom
34 | import
35 |
36 |
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-web
42 |
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-data-jpa
47 |
48 |
49 | org.apache.derby
50 | derby
51 | runtime
52 |
53 |
54 | com.fasterxml.jackson.core
55 | jackson-core
56 |
57 |
58 | com.fasterxml.jackson.core
59 | jackson-annotations
60 |
61 |
62 | com.fasterxml.jackson.core
63 | jackson-databind
64 |
65 |
66 | com.fasterxml.jackson.module
67 | jackson-module-parameter-names
68 |
69 |
70 | com.fasterxml.jackson.datatype
71 | jackson-datatype-jdk8
72 |
73 |
74 | com.fasterxml.jackson.datatype
75 | jackson-datatype-jsr310
76 |
77 |
78 | org.apache.derby
79 | derby
80 | runtime
81 |
82 |
83 | org.springframework.boot
84 | spring-boot-starter-test
85 | test
86 |
87 |
88 |
89 |
90 |
91 |
92 | org.springframework.boot
93 | spring-boot-maven-plugin
94 |
95 |
96 |
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/simluation-project-startup.bat:
--------------------------------------------------------------------------------
1 | @java -jar target/simulation-project-0.0.1-SNAPSHOT.jar
2 | @pause
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/AjaxResponse.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.core;
2 |
3 | public class AjaxResponse {
4 | private static final String CODE_SUCCESS="ok",CODE_ERROR="error";
5 |
6 | /**应答的代号*/
7 | private String code;
8 | private String message;
9 | private Object data;
10 |
11 | public String getCode() {
12 | return code;
13 | }
14 | public void setCode(String code) {
15 | this.code = code;
16 | }
17 | public String getMessage() {
18 | return message;
19 | }
20 | public void setMessage(String message) {
21 | this.message = message;
22 | }
23 | public Object getData() {
24 | return data;
25 | }
26 | public void setData(Object data) {
27 | this.data = data;
28 | }
29 | public static AjaxResponse ok() {
30 | return ok(null);
31 | }
32 | public static AjaxResponse ok(Object data) {
33 | AjaxResponse ar=new AjaxResponse();
34 | ar.setCode(CODE_SUCCESS);
35 | ar.setData(data);
36 | return ar;
37 | }
38 | public static AjaxResponse fail(String message) {
39 | return fail(CODE_ERROR,message);
40 | }
41 | public static AjaxResponse fail(Throwable e) {
42 | return fail(CODE_ERROR,e.getMessage());
43 | }
44 | public static AjaxResponse fail(String code,Throwable e) {
45 | return fail(CODE_ERROR,e.getMessage());
46 | }
47 | public static AjaxResponse fail(String code,String message) {
48 | AjaxResponse ar=new AjaxResponse();
49 | ar.setCode(code);
50 | ar.setMessage(message);
51 | ar.setData(null);
52 | return ar;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/AssertThrowUtil.java:
--------------------------------------------------------------------------------
1 | /**
2 | * shidao
3 | * FunctionTempldate.java
4 | * 2016年1月20日
5 | */
6 | package com.yizhuoyan.core;
7 |
8 |
9 |
10 | import java.util.Collection;
11 |
12 | /**
13 | * 数据验证工具类
14 | *
15 | * @author root@yizhuoyan.com
16 | */
17 |
18 | public class AssertThrowUtil{
19 |
20 |
21 | static private void throwException(String message, Object... args){
22 | throw new PlatformException(handleMessageArguments(message,args));
23 | }
24 |
25 |
26 | private static String handleMessageArguments(String message,Object... args){
27 | StringBuilder result=new StringBuilder(message);
28 | if(args.length>0){
29 | result.append("(");
30 | for (Object arg : args) {
31 | result.append(arg).append(',');
32 | }
33 | result.setCharAt(result.length()-1,')');
34 | }
35 | return result.toString();
36 | }
37 |
38 | static public void assertNull(String message, Object obj, Object... args){
39 | if(obj!=null) throwException(message, args);
40 | }
41 |
42 | static public void assertNotNull(String message, Object obj, Object... args){
43 | if(obj==null)
44 | throwException(message, args);
45 | }
46 |
47 | /**
48 | * 断言字符串是null或者空字符串或空白字符串
49 | *
50 | * @param message
51 | * @param s
52 | * @param args
53 | */
54 | static public void assertBlank(String message, String s, Object... args){
55 | if(s!=null&&s.trim().length()!=0){
56 | throwException(message, args);
57 | }
58 | }
59 |
60 | static public String assertNotBlank(String message, String s,
61 | Object... args){
62 | if(s==null||(s = s.trim()).length()==0){
63 | throwException(message, args);
64 | }
65 | return s;
66 | }
67 |
68 |
69 | static public int assertInteger(String message, String intStr,
70 | Object... args){
71 | if(intStr==null||intStr.trim().length()==0){
72 | throwException(message, args);
73 | }
74 | try{
75 | return Integer.parseInt(intStr);
76 | }catch(Exception e){
77 | throwException(message, args);
78 | }
79 | return 0;
80 | }
81 |
82 | static public void assertNotEquals(String message, Object a, Object b,
83 | Object... args){
84 | if(a==null ? null==b : a.equals(b)){
85 | throwException(message, args);
86 | }
87 | }
88 |
89 | static public void assertEquals(String message, Object a, Object b,
90 | Object... args){
91 | if(a==null ? null!=b : !a.equals(b)){
92 | throwException(message, args);
93 | }
94 | }
95 |
96 | static public Collection assertEmpty(String message, Collection b,
97 | Object... args){
98 | if(b==null||b.size()!=0){
99 | throwException(message, args);
100 | }
101 | return b;
102 | }
103 |
104 | static public Collection assertNotEmpty(String message, Collection b,
105 | Object... args){
106 | if(b!=null&&b.size()==0){
107 | throwException(message, args);
108 | }
109 | return b;
110 | }
111 |
112 | static public void assertTrue(String message, boolean b, Object... args){
113 | if(!b){
114 | throwException(message, args);
115 | }
116 | }
117 |
118 | static public void assertFalse(String message, boolean b, Object... args){
119 | if(b){
120 | throwException(message, args);
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/JsonUtil.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.core;
2 |
3 | import com.fasterxml.jackson.annotation.JsonInclude.Include;
4 | import com.fasterxml.jackson.databind.MapperFeature;
5 | import com.fasterxml.jackson.databind.ObjectMapper;
6 | import com.fasterxml.jackson.databind.SerializationFeature;
7 |
8 | public class JsonUtil {
9 | private static ObjectMapper JSON_MAPPER = new ObjectMapper();
10 | static {
11 | JSON_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
12 | JSON_MAPPER.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
13 | JSON_MAPPER.setSerializationInclusion(Include.NON_NULL);
14 | //JSON_MAPPER.registerModule(new JavaTimeModule());
15 | }
16 |
17 | public static String toJsonString(Object o) {
18 | try {
19 | return JSON_MAPPER.writeValueAsString(o);
20 | } catch (Exception e) {
21 | throw new RuntimeException(e);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/PlatformException.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.core;
2 |
3 | /**
4 | * 全局异常类
5 | * @author yizhuoyan@hotmail.com
6 | *
7 | */
8 | public class PlatformException extends RuntimeException {
9 |
10 | public PlatformException(String message, Throwable cause) {
11 | super(message, cause);
12 | }
13 |
14 | public PlatformException(String message) {
15 | super(message);
16 | }
17 |
18 | public static void throwWithMessage(String message,Object... args) {
19 | for (int i = 0; i < args.length; i++) {
20 | message=message.replaceFirst("\\?",String.valueOf(args[0]));
21 | }
22 | throw new PlatformException(message);
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/ThisSystemUtil.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.core;
2 |
3 | import java.security.MessageDigest;
4 |
5 | import sun.misc.BASE64Encoder;
6 |
7 | public class ThisSystemUtil {
8 | public static String md5(String s) {
9 | try {
10 | s+="^oa$";
11 | // 确定计算方法
12 | MessageDigest md5 = MessageDigest.getInstance("MD5");
13 | BASE64Encoder base64en = new BASE64Encoder();
14 | // 加密后的字符串
15 | String newstr = base64en.encode(md5.digest(s.getBytes("utf-8")));
16 | return newstr;
17 | } catch (Exception e) {
18 | throw new RuntimeException(e);
19 | }
20 | }
21 |
22 | public static boolean isBlank(String s) {
23 | return s==null||s.trim().length()==0;
24 | }
25 | /**
26 | * 清理字符串前后空格,如果字符串为空白字符串,则返回null
27 | *
28 | * @param s
29 | * @return
30 | */
31 | public static String $(String s) {
32 | if (s != null) {
33 | if ((s = s.trim()).length() == 0)
34 | return null;
35 | else
36 | return s;
37 | }
38 | return null;
39 | }
40 |
41 | /**
42 | * 解析字符串为整数
43 | *
44 | * @param s
45 | * @param defaultInt
46 | * @return
47 | */
48 | public static int parseInt(String s, int defaultInt) {
49 | try {
50 | return Integer.parseInt(s);
51 | } catch (Exception e) {
52 | return defaultInt;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/core/UserContext.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.core;
2 |
3 | import java.time.Instant;
4 | import java.util.Date;
5 |
6 | /**
7 | * 用户上下文
8 | * 包含用户的信息
9 | * @author yizhuoyan@hotmail.com
10 | *
11 | */
12 | public class UserContext {
13 |
14 | private String id;
15 | private String account;
16 | private String name;
17 | private Instant lastLoginTime;
18 | private String lastLoginIp;
19 | private String token;
20 |
21 | public String getToken() {
22 | return token;
23 | }
24 |
25 | public void setToken(String token) {
26 | this.token = token;
27 | }
28 |
29 | public String getLastLoginIp() {
30 | return lastLoginIp;
31 | }
32 | public void setLastLoginIp(String lastLoginIp) {
33 | this.lastLoginIp = lastLoginIp;
34 | }
35 |
36 | public String getId() {
37 | return id;
38 | }
39 | public void setId(String id) {
40 | this.id = id;
41 | }
42 | public String getAccount() {
43 | return account;
44 | }
45 | public void setAccount(String account) {
46 | this.account = account;
47 | }
48 | public Instant getLastLoginTime() {
49 | return lastLoginTime;
50 | }
51 | public void setLastLoginTime(Instant lastLoginTime) {
52 | this.lastLoginTime = lastLoginTime;
53 | }
54 | public String getName() {
55 | return name;
56 | }
57 | public void setName(String name) {
58 | this.name = name;
59 | }
60 |
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/AjaxApplication.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo;
2 |
3 | import com.fasterxml.jackson.annotation.JsonInclude;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import com.fasterxml.jackson.databind.SerializationFeature;
6 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
7 | import org.springframework.beans.factory.annotation.Configurable;
8 | import org.springframework.boot.SpringApplication;
9 | import org.springframework.boot.autoconfigure.SpringBootApplication;
10 | import org.springframework.context.annotation.Bean;
11 | import org.springframework.context.annotation.Configuration;
12 | import org.springframework.web.cors.CorsConfiguration;
13 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
14 | import org.springframework.web.filter.CorsFilter;
15 |
16 | @SpringBootApplication
17 | @Configuration
18 | public class AjaxApplication {
19 |
20 | @Bean
21 | public ObjectMapper jacksonConfig(){
22 | ObjectMapper mapper=new ObjectMapper();
23 | mapper.enable(SerializationFeature.INDENT_OUTPUT);
24 | mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
25 | mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
26 | mapper.registerModule(new JavaTimeModule());
27 | return mapper;
28 | }
29 |
30 | @Bean
31 | public CorsFilter corsFilter() {
32 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
33 | CorsConfiguration corsConfiguration = new CorsConfiguration();
34 | corsConfiguration.addAllowedOrigin("*");
35 | corsConfiguration.addAllowedHeader("*");
36 | corsConfiguration.addAllowedMethod("*");
37 | source.registerCorsConfiguration("/**", corsConfiguration);
38 | return new CorsFilter(source);
39 | }
40 |
41 |
42 |
43 |
44 | public static void main(String[] args) {
45 |
46 | SpringApplication.run(AjaxApplication.class, args);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/AuthorizationInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller;
2 |
3 | import com.yizhuoyan.core.ThisSystemUtil;
4 | import com.yizhuoyan.teaching.demo.core.EncrypDES;
5 | import org.springframework.util.StringUtils;
6 | import org.springframework.web.servlet.HandlerInterceptor;
7 | import org.springframework.web.servlet.ModelAndView;
8 |
9 | import javax.servlet.*;
10 | import javax.servlet.annotation.WebFilter;
11 | import javax.servlet.http.HttpServletRequest;
12 | import javax.servlet.http.HttpServletResponse;
13 | import java.io.IOException;
14 |
15 | /**
16 | * Created by Administrator on 18/04/17.
17 | */
18 |
19 | public class AuthorizationInterceptor implements HandlerInterceptor {
20 | @Override
21 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
22 | String uri=request.getRequestURI();
23 | System.out.println(uri);
24 | String token=request.getParameter("token");
25 | if(token==null){
26 | token=request.getHeader("token");
27 | }
28 | if(StringUtils.hasText(token)){
29 | try {
30 | String account = EncrypDES.decryptor(token);
31 | request.setAttribute("account",account);
32 | return true;
33 | }catch (Exception e){
34 | request.setAttribute("reason","非法token");
35 | }
36 | }else{
37 | request.setAttribute("reason","请在请求头中传入token");
38 | }
39 | request.getRequestDispatcher("/noAuthorizaiton.do").forward(request,response);
40 | return false;
41 | }
42 |
43 | @Override
44 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
45 |
46 | }
47 |
48 | @Override
49 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/LogHandler.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller;
2 |
3 | import com.yizhuoyan.core.AjaxResponse;
4 | import com.yizhuoyan.core.PlatformException;
5 | import com.yizhuoyan.core.UserContext;
6 | import com.yizhuoyan.teaching.demo.controller.ao.ModifyPasswordAo;
7 | import com.yizhuoyan.teaching.demo.controller.ao.UpdateUserAo;
8 | import com.yizhuoyan.teaching.demo.controller.ao.UserAo;
9 | import com.yizhuoyan.teaching.demo.core.EncrypDES;
10 | import com.yizhuoyan.teaching.demo.core.PaginationQueryResult;
11 | import com.yizhuoyan.teaching.demo.core.ThisSystemUtil;
12 | import com.yizhuoyan.teaching.demo.entity.SecurityLogEntity;
13 | import com.yizhuoyan.teaching.demo.function.LogService;
14 | import com.yizhuoyan.teaching.demo.function.UserFunction;
15 | import org.springframework.beans.factory.annotation.Autowired;
16 | import org.springframework.web.bind.annotation.PostMapping;
17 | import org.springframework.web.bind.annotation.RequestMapping;
18 | import org.springframework.web.bind.annotation.RestController;
19 |
20 | import javax.servlet.http.HttpServletRequest;
21 |
22 | /**
23 | * Created by Administrator on 18/04/16.
24 | */
25 | @RestController
26 | @RequestMapping("/log")
27 | public class LogHandler {
28 |
29 | @Autowired
30 | private LogService logService;
31 |
32 |
33 | @PostMapping("/list.do")
34 | public AjaxResponse list(String key,String pageNo,String pageSize) throws Throwable {
35 | try {
36 | int pageNoInt= ThisSystemUtil.parseInt(pageNo,-1);
37 | int pageSiseInt=ThisSystemUtil.parseInt(pageSize,-1);
38 |
39 | PaginationQueryResult result= logService.find(key,pageNoInt,pageSiseInt);
40 |
41 | return AjaxResponse.ok(result);
42 |
43 | } catch (PlatformException e) {
44 | return AjaxResponse.fail(e);
45 | }finally {
46 | }
47 | }
48 |
49 | }
50 |
51 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/NoAuthorizationHandler.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller;
2 |
3 | import com.yizhuoyan.core.AjaxResponse;
4 | import org.springframework.web.bind.annotation.ModelAttribute;
5 | import org.springframework.web.bind.annotation.RequestAttribute;
6 | import org.springframework.web.bind.annotation.RequestMapping;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | /**
10 | * Created by Administrator on 18/04/17.
11 | */
12 | @RestController
13 | public class NoAuthorizationHandler {
14 | @RequestMapping("/noAuthorizaiton.do")
15 | public AjaxResponse hanler(@RequestAttribute String reason){
16 | if(reason==null){
17 | reason="无token或token无效";
18 | }
19 | return AjaxResponse.fail(reason);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/SimpleAjaxHandler.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller;
2 |
3 | import com.yizhuoyan.core.AjaxResponse;
4 | import com.yizhuoyan.core.AssertThrowUtil;
5 | import com.yizhuoyan.core.PlatformException;
6 | import com.yizhuoyan.core.ThisSystemUtil;
7 | import com.yizhuoyan.teaching.demo.core.RMBUpper;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RequestMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import java.math.BigDecimal;
13 |
14 | /**
15 | * Created by Administrator on 18/04/17.
16 | */
17 | @RestController
18 | @RequestMapping("/simple")
19 | public class SimpleAjaxHandler {
20 |
21 | @GetMapping("/upper.do")
22 | public AjaxResponse upperString(String target){
23 | try {
24 | if (ThisSystemUtil.isBlank(target)) {
25 | throw new PlatformException("target必须填写");
26 | }
27 | target = target.trim();
28 | return AjaxResponse.ok(target.toUpperCase());
29 | }catch(PlatformException e){
30 | return AjaxResponse.fail(e);
31 | }
32 | }
33 |
34 | @GetMapping("/rmbUpper.do")
35 | public AjaxResponse rmbUpper(String rmb){
36 | try {
37 | if (ThisSystemUtil.isBlank(rmb)) {
38 | throw new PlatformException("rmb必须填写");
39 | }
40 |
41 | String result=RMBUpper.convertCurrency(rmb);
42 | return AjaxResponse.ok(result);
43 | }catch(PlatformException|IllegalArgumentException e){
44 | return AjaxResponse.fail(e);
45 | }
46 | }
47 |
48 | @RequestMapping("/sum.do")
49 | public AjaxResponse sum(String a,String b){
50 | try {
51 | a= AssertThrowUtil.assertNotBlank("a不能为空",a);
52 | b= AssertThrowUtil.assertNotBlank("b不能为空",b);
53 |
54 | BigDecimal aBig,bBig;
55 |
56 | try {
57 | aBig=new BigDecimal(a);
58 | }catch(Exception e){
59 | throw new PlatformException("a数字格式错误");
60 | }
61 | try {
62 | bBig=new BigDecimal(b);
63 | }catch(Exception e){
64 |
65 | throw new PlatformException("b数字格式错误");
66 | }
67 | try {
68 | Thread.sleep(3000);
69 | }catch (Exception e){}
70 | return AjaxResponse.ok(aBig.add(bBig).toPlainString());
71 | }catch(PlatformException e){
72 | return AjaxResponse.fail(e);
73 | }
74 | }
75 |
76 |
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/UserHandler.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller;
2 |
3 | import com.yizhuoyan.core.AjaxResponse;
4 | import com.yizhuoyan.core.PlatformException;
5 | import com.yizhuoyan.core.UserContext;
6 | import com.yizhuoyan.teaching.demo.controller.ao.ModifyPasswordAo;
7 | import com.yizhuoyan.teaching.demo.controller.ao.UpdateUserAo;
8 | import com.yizhuoyan.teaching.demo.controller.ao.UserAo;
9 | import com.yizhuoyan.teaching.demo.core.EncrypDES;
10 | import com.yizhuoyan.teaching.demo.entity.SecurityLogEntity;
11 | import com.yizhuoyan.teaching.demo.entity.UserEntity;
12 | import com.yizhuoyan.teaching.demo.function.LogService;
13 | import com.yizhuoyan.teaching.demo.function.UserFunction;
14 | import org.springframework.beans.factory.annotation.Autowired;
15 | import org.springframework.web.bind.annotation.PostMapping;
16 | import org.springframework.web.bind.annotation.RequestMapping;
17 | import org.springframework.web.bind.annotation.RestController;
18 |
19 | import javax.servlet.http.HttpServletRequest;
20 | import javax.servlet.http.HttpServletResponse;
21 | import java.time.Instant;
22 | import java.util.Objects;
23 | import java.util.regex.Pattern;
24 |
25 | import static com.yizhuoyan.core.AssertThrowUtil.*;
26 |
27 | /**
28 | * Created by Administrator on 18/04/16.
29 | */
30 | @RestController
31 | @RequestMapping("/user")
32 | public class UserHandler {
33 |
34 | @Autowired
35 | private UserFunction fun;
36 | @Autowired
37 | private LogService logService;
38 |
39 |
40 | @RequestMapping("/login.do")
41 | public AjaxResponse login(String account, String password, HttpServletRequest req, HttpServletResponse resp) throws Exception {
42 | SecurityLogEntity log=new SecurityLogEntity();
43 | try {
44 | UserContext uc = fun.login(account, password);
45 | //生成token
46 | String token= EncrypDES.encrytor(account);
47 | uc.setToken(token);
48 | log.setResultHow("登陆成功!");
49 | return AjaxResponse.ok(uc);
50 |
51 | } catch (PlatformException e) {
52 | log.setResultHow("登陆失败");
53 | log.setResultWhy(e);
54 | return AjaxResponse.fail(e);
55 | }finally {
56 | log.setIp(req.getRemoteAddr());
57 | log.setOccurWho(account);
58 | log.setDoWhat(String.format("使用%s尝试登陆",account));
59 | logService.log(log);
60 | }
61 | }
62 |
63 | @RequestMapping("/logout.do")
64 | public AjaxResponse logout(HttpServletRequest req) throws Throwable {
65 | SecurityLogEntity log=new SecurityLogEntity();
66 | try {
67 |
68 | String account=(String)req.getAttribute("account");
69 | log.setOccurWho(account);
70 | req.getSession().invalidate();
71 | return AjaxResponse.ok();
72 | } catch (PlatformException e) {
73 | return AjaxResponse.fail(e);
74 | }finally {
75 | log.setIp(req.getRemoteAddr());
76 | log.setDoWhat("注销");
77 | logService.log(log);
78 | }
79 | }
80 |
81 |
82 | @PostMapping("/register.do")
83 | public AjaxResponse register(UserAo ao,HttpServletRequest req) throws Throwable {
84 | SecurityLogEntity log=new SecurityLogEntity();
85 | try {
86 | log.setOccurWho(ao.getAccount());
87 | fun.registerUser(ao);
88 | log.setResultHow("注册成功");
89 | return AjaxResponse.ok();
90 |
91 | } catch (PlatformException e) {
92 | log.setResultHow("注册失败");
93 | log.setResultWhy(e);
94 | return AjaxResponse.fail(e);
95 | }finally {
96 | log.setIp(req.getRemoteAddr());
97 | log.setDoWhat("注册");
98 | logService.log(log);
99 | }
100 |
101 | }
102 |
103 | @PostMapping("/modifyPassword.do")
104 | public AjaxResponse modifyPassword(ModifyPasswordAo ao,HttpServletRequest req) throws Throwable {
105 | SecurityLogEntity log=new SecurityLogEntity();
106 | log.setOccurWho(ao.getAccount());
107 | try {
108 |
109 | fun.modifyPassword(ao);
110 | log.setResultHow("成功");
111 | return AjaxResponse.ok();
112 |
113 | } catch (PlatformException e) {
114 | log.setResultHow("失败");
115 | log.setResultWhy(e);
116 | return AjaxResponse.fail(e);
117 | }finally {
118 | log.setIp(req.getRemoteAddr());
119 | log.setDoWhat("修改密码");
120 | log.setOccurWho(ao.getAccount());
121 | logService.log(log);
122 | }
123 | }
124 |
125 | @RequestMapping("/existAccount.do")
126 | public AjaxResponse existAccount(String account) throws Throwable {
127 | try {
128 |
129 | boolean result=fun.existAccount(account);
130 | return AjaxResponse.ok(result);
131 |
132 | } catch (PlatformException e) {
133 | return AjaxResponse.fail(e);
134 | }
135 | }
136 |
137 |
138 | @PostMapping("/modify.do")
139 | public AjaxResponse modify(UpdateUserAo ao,HttpServletRequest req) throws Throwable {
140 | SecurityLogEntity log=new SecurityLogEntity();
141 | log.setOccurWho(ao.getAccount());
142 | try {
143 |
144 | fun.updateUser(ao);
145 | log.setResultHow("成功");
146 | return AjaxResponse.ok();
147 |
148 | } catch (PlatformException e) {
149 | log.setResultHow("失败");
150 | log.setResultWhy(e);
151 | return AjaxResponse.fail(e);
152 | }finally {
153 | log.setIp(req.getRemoteAddr());
154 | log.setDoWhat("修改个人信息");
155 | log.setOccurWho(ao.getAccount());
156 | logService.log(log);
157 | }
158 | }
159 |
160 | }
161 |
162 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/ao/ModifyPasswordAo.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller.ao;
2 |
3 | /**
4 | * Created by Administrator on 18/04/17.
5 | */
6 | public class ModifyPasswordAo {
7 | private String account;
8 | private String oldPassword;
9 | private String newPassword;
10 | private String newPasswordConfirm;
11 |
12 | public String getAccount() {
13 | return account;
14 | }
15 |
16 | public void setAccount(String account) {
17 | this.account = account;
18 | }
19 |
20 | public String getOldPassword() {
21 | return oldPassword;
22 | }
23 |
24 | public void setOldPassword(String oldPassword) {
25 | this.oldPassword = oldPassword;
26 | }
27 |
28 | public String getNewPassword() {
29 | return newPassword;
30 | }
31 |
32 | public void setNewPassword(String newPassword) {
33 | this.newPassword = newPassword;
34 | }
35 |
36 | public String getNewPasswordConfirm() {
37 | return newPasswordConfirm;
38 | }
39 |
40 | public void setNewPasswordConfirm(String newPasswordConfirm) {
41 | this.newPasswordConfirm = newPasswordConfirm;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/ao/UpdateUserAo.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller.ao;
2 |
3 | /**
4 | * Created by Administrator on 18/04/17.
5 | */
6 | public class UpdateUserAo {
7 | private String id;
8 | private String account;
9 | private String name;
10 |
11 | public String getId() {
12 | return id;
13 | }
14 |
15 | public void setId(String id) {
16 | this.id = id;
17 | }
18 |
19 | public String getAccount() {
20 | return account;
21 | }
22 |
23 | public void setAccount(String account) {
24 | this.account = account;
25 | }
26 |
27 | public String getName() {
28 | return name;
29 | }
30 |
31 | public void setName(String name) {
32 | this.name = name;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/controller/ao/UserAo.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.controller.ao;
2 |
3 | /**
4 | * Created by Administrator on 18/04/17.
5 | */
6 | public class UserAo {
7 | private String account;
8 | private String name;
9 | private String password;
10 | private String passwordConfirm;
11 |
12 | public String getName() {
13 | return name;
14 | }
15 |
16 | public void setName(String name) {
17 | this.name = name;
18 | }
19 |
20 | public String getPassword() {
21 | return password;
22 | }
23 |
24 | public void setPassword(String password) {
25 | this.password = password;
26 | }
27 |
28 | public String getPasswordConfirm() {
29 | return passwordConfirm;
30 | }
31 |
32 | public void setPasswordConfirm(String passwordConfirm) {
33 | this.passwordConfirm = passwordConfirm;
34 | }
35 |
36 | public String getAccount() {
37 | return account;
38 | }
39 |
40 | public void setAccount(String account) {
41 | this.account = account;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/AjaxResponse.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | public class AjaxResponse {
4 | private static final String CODE_SUCCESS="ok",CODE_ERROR="error";
5 |
6 | /**应答的代号*/
7 | private String code;
8 | private String message;
9 | private Object data;
10 |
11 | public String getCode() {
12 | return code;
13 | }
14 | public void setCode(String code) {
15 | this.code = code;
16 | }
17 | public String getMessage() {
18 | return message;
19 | }
20 | public void setMessage(String message) {
21 | this.message = message;
22 | }
23 | public Object getData() {
24 | return data;
25 | }
26 | public void setData(Object data) {
27 | this.data = data;
28 | }
29 | public static AjaxResponse ok() {
30 | return ok(null);
31 | }
32 | public static AjaxResponse ok(Object data) {
33 | AjaxResponse ar=new AjaxResponse();
34 | ar.setCode(CODE_SUCCESS);
35 | ar.setData(data);
36 | return ar;
37 | }
38 | public static AjaxResponse fail(String message) {
39 | return fail(CODE_ERROR,message);
40 | }
41 | public static AjaxResponse fail(Throwable e) {
42 | return fail(CODE_ERROR,e.getMessage());
43 | }
44 | public static AjaxResponse fail(String code,Throwable e) {
45 | return fail(CODE_ERROR,e.getMessage());
46 | }
47 | public static AjaxResponse fail(String code,String message) {
48 | AjaxResponse ar=new AjaxResponse();
49 | ar.setCode(code);
50 | ar.setMessage(message);
51 | ar.setData(null);
52 | return ar;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/AssertThrowUtil.java:
--------------------------------------------------------------------------------
1 | /**
2 | * shidao
3 | * FunctionTempldate.java
4 | * 2016年1月20日
5 | */
6 | package com.yizhuoyan.teaching.demo.core;
7 |
8 |
9 |
10 | import com.yizhuoyan.core.PlatformException;
11 |
12 | import java.util.Collection;
13 |
14 | /**
15 | * 数据验证工具类
16 | *
17 | * @author root@yizhuoyan.com
18 | */
19 |
20 | public class AssertThrowUtil{
21 |
22 |
23 | static private void throwException(String message, Object... args){
24 | throw new PlatformException(handleMessageArguments(message,args));
25 | }
26 |
27 |
28 | private static String handleMessageArguments(String message,Object... args){
29 | StringBuilder result=new StringBuilder(message);
30 | if(args.length>0){
31 | result.append("(");
32 | for (Object arg : args) {
33 | result.append(arg).append(',');
34 | }
35 | result.setCharAt(result.length()-1,')');
36 | }
37 | return result.toString();
38 | }
39 |
40 | static public void assertNull(String message, Object obj, Object... args){
41 | if(obj!=null) throwException(message, args);
42 | }
43 |
44 | static public void assertNotNull(String message, Object obj, Object... args){
45 | if(obj==null)
46 | throwException(message, args);
47 | }
48 |
49 | /**
50 | * 断言字符串是null或者空字符串或空白字符串
51 | *
52 | * @param message
53 | * @param s
54 | * @param args
55 | */
56 | static public void assertBlank(String message, String s, Object... args){
57 | if(s!=null&&s.trim().length()!=0){
58 | throwException(message, args);
59 | }
60 | }
61 |
62 | static public String assertNotBlank(String message, String s,
63 | Object... args){
64 | if(s==null||(s = s.trim()).length()==0){
65 | throwException(message, args);
66 | }
67 | return s;
68 | }
69 |
70 |
71 | static public int assertInteger(String message, String intStr,
72 | Object... args){
73 | if(intStr==null||intStr.trim().length()==0){
74 | throwException(message, args);
75 | }
76 | try{
77 | return Integer.parseInt(intStr);
78 | }catch(Exception e){
79 | throwException(message, args);
80 | }
81 | return 0;
82 | }
83 |
84 | static public void assertNotEquals(String message, Object a, Object b,
85 | Object... args){
86 | if(a==null ? null==b : a.equals(b)){
87 | throwException(message, args);
88 | }
89 | }
90 |
91 | static public void assertEquals(String message, Object a, Object b,
92 | Object... args){
93 | if(a==null ? null!=b : !a.equals(b)){
94 | throwException(message, args);
95 | }
96 | }
97 |
98 | static public Collection assertEmpty(String message, Collection b,
99 | Object... args){
100 | if(b==null||b.size()!=0){
101 | throwException(message, args);
102 | }
103 | return b;
104 | }
105 |
106 | static public Collection assertNotEmpty(String message, Collection b,
107 | Object... args){
108 | if(b!=null&&b.size()==0){
109 | throwException(message, args);
110 | }
111 | return b;
112 | }
113 |
114 | static public void assertTrue(String message, boolean b, Object... args){
115 | if(!b){
116 | throwException(message, args);
117 | }
118 | }
119 |
120 | static public void assertFalse(String message, boolean b, Object... args){
121 | if(b){
122 | throwException(message, args);
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/EncrypDES.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 | import javax.crypto.Cipher;
3 | import javax.crypto.KeyGenerator;
4 | import javax.crypto.SecretKey;
5 | import java.security.Security;
6 | import java.util.Arrays;
7 |
8 | public class EncrypDES {
9 |
10 | //KeyGenerator 提供对称密钥生成器的功能,支持各种算法
11 | private static KeyGenerator keygen;
12 | //SecretKey 负责保存对称密钥
13 | private static SecretKey deskey;
14 | static{
15 | init();
16 | }
17 | private static void init(){
18 | try {
19 | Security.addProvider(new com.sun.crypto.provider.SunJCE());
20 | keygen = KeyGenerator.getInstance("DES");
21 | deskey=keygen.generateKey();
22 |
23 | }catch (Exception e){
24 | e.printStackTrace();
25 | }
26 | }
27 |
28 |
29 | /**
30 | * 对字符串加密
31 | *
32 | */
33 | public static String encrytor(String str) throws Exception {
34 | // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
35 | Cipher c = Cipher.getInstance("DES");
36 | c.init(Cipher.ENCRYPT_MODE, deskey);
37 | byte[] src = str.getBytes();
38 | // 加密,结果保存进cipherByte
39 | src= c.doFinal(src);
40 | //转换为32进制
41 | StringBuilder result=new StringBuilder();
42 | for(byte b:src){
43 | result.append(Integer.toString(Byte.toUnsignedInt(b),32));
44 | result.append("-");
45 | }
46 | result.deleteCharAt(result.length()-1);
47 | System.out.println(Arrays.toString(src));
48 | return result.toString();
49 | }
50 |
51 | /**
52 | * 对字符串解密
53 | *
54 | */
55 | public static String decryptor(String str) throws Exception {
56 | String[] cs=str.split("-");
57 | byte[] buff=new byte[cs.length];
58 | int i=0;
59 | for(String s:cs){
60 | int v=Integer.parseInt(s,32);
61 | buff[i++]=(byte)v;
62 | }
63 | Cipher c=Cipher.getInstance("DES");
64 | c.init(Cipher.DECRYPT_MODE, deskey);
65 | buff=c.doFinal(buff);
66 | return new String(buff);
67 | }
68 |
69 |
70 |
71 | public static void main(String[] args) throws Exception {
72 | String msg ="你大爷";
73 | String encontent = encrytor(msg);
74 | String decontent = decryptor(encontent);
75 | System.out.println("明文是:" + msg);
76 | System.out.println("加密后:" + encontent);
77 | System.out.println("解密后:" + decontent);
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/JsonUtil.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | import com.fasterxml.jackson.annotation.JsonInclude.Include;
4 | import com.fasterxml.jackson.databind.MapperFeature;
5 | import com.fasterxml.jackson.databind.ObjectMapper;
6 | import com.fasterxml.jackson.databind.SerializationFeature;
7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
8 |
9 | public class JsonUtil {
10 | private static ObjectMapper JSON_MAPPER = new ObjectMapper();
11 | static {
12 |
13 | }
14 |
15 | public static String toJsonString(Object o) {
16 | try {
17 | return JSON_MAPPER.writeValueAsString(o);
18 | } catch (Exception e) {
19 | throw new RuntimeException(e);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/PaginationQueryResult.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 |
4 | import java.io.Serializable;
5 | import java.util.HashMap;
6 | import java.util.List;
7 | import java.util.Map;
8 | import java.util.function.Function;
9 |
10 |
11 | public class PaginationQueryResult implements Serializable {
12 | private int totalRows = -1;
13 | private int totalPages = -1;
14 | private int pageSize = -1;
15 | private int pageNo = -1;
16 | private List rows;
17 |
18 | public PaginationQueryResult() {
19 |
20 | }
21 | public PaginationQueryResult(long totalSize, List rows) {
22 | this.setTotalRows(totalSize);
23 | this.rows = rows;
24 | }
25 |
26 | public void setRows(List rows) {
27 | this.rows = rows;
28 | }
29 |
30 | public List getRows() {
31 | return rows;
32 | }
33 |
34 |
35 | public int getTotalRows() {
36 | return this.totalRows;
37 | }
38 |
39 | public void setTotalRows(int totalRows) {
40 | this.totalRows = totalRows;
41 | }
42 |
43 | public void setTotalRows(long totalRows) {
44 | this.totalRows = (int) totalRows;
45 | }
46 |
47 | public int getTotalPages() {
48 | if (this.totalRows <= 0) return 0;
49 | int tp = this.totalPages;
50 | if (tp == -1) {
51 | int tr = this.getTotalRows();
52 | int ps = this.getPageSize();
53 | tp = tr / ps;
54 | if ((tr % ps) != 0) {
55 | tp++;
56 | }
57 | }
58 | return tp;
59 | }
60 |
61 | public int getPageSize() {
62 | return pageSize;
63 | }
64 |
65 | public void setPageSize(int pageSize) {
66 | this.pageSize = pageSize;
67 | }
68 |
69 | public int getPageNo() {
70 | return pageNo;
71 | }
72 |
73 | public void setPageNo(int pageNo) {
74 | this.pageNo = pageNo;
75 | }
76 |
77 | public Map toJSON(Function transfer) {
78 | Map map = new HashMap<>();
79 | if (this.totalRows > 0) {
80 | int z = this.rows.size();
81 | Map[] arr = new Map[z];
82 | while (z-- > 0) {
83 | arr[z] = transfer.apply(this.rows.get(z));
84 | }
85 | map.put("rows", arr);
86 | map.put("totalPages", this.getTotalPages());
87 | } else {
88 | map.put("rows", new Object[0]);
89 | map.put("totalPages", 0);
90 | }
91 | map.put("pageNo", this.getPageNo());
92 | map.put("pageSize", this.getPageSize());
93 | map.put("totalRows", this.getTotalRows());
94 |
95 |
96 | return map;
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/PlatformException.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | /**
4 | * 全局异常类
5 | * @author yizhuoyan@hotmail.com
6 | *
7 | */
8 | public class PlatformException extends RuntimeException {
9 |
10 | public PlatformException(String message, Throwable cause) {
11 | super(message, cause);
12 | }
13 |
14 | public PlatformException(String message) {
15 | super(message);
16 | }
17 |
18 | public static void throwWithMessage(String message,Object... args) {
19 | for (int i = 0; i < args.length; i++) {
20 | message=message.replaceFirst("\\?",String.valueOf(args[0]));
21 | }
22 | throw new PlatformException(message);
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/RMBUpper.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | import javax.xml.bind.SchemaOutputResolver;
4 | import java.math.BigDecimal;
5 | import java.math.MathContext;
6 |
7 | /**
8 | * Created by Administrator on 18/04/17.
9 | */
10 | public class RMBUpper {
11 | //定义相关常量
12 | private static final char[] DIGIT_CHARS = "零壹贰叁肆伍陆柒捌玖".toCharArray();
13 | private static final char[] UNIT_CHARS ="元角分整".toCharArray();
14 | private static final String[] RADIX_CHARS = new String[]{"","拾","佰", "仟", "万", "亿"};
15 |
16 | /**
17 | * 人民大写转换
18 | *@param {string} currencyStr 金额字符串
19 | */
20 | public static String convertCurrency(String currencyStr) {
21 | //1 验证输入
22 | if (currencyStr==null||(currencyStr=currencyStr.trim()).length() == 0) {
23 | throw new IllegalArgumentException("金额不能为空");
24 | }
25 | //2去掉,空格
26 | currencyStr = currencyStr.replaceAll("[, ]","");
27 |
28 | if (currencyStr.length() == 0) {
29 | throw new IllegalArgumentException("金额格式错误");
30 | }
31 | //3验证格式
32 | BigDecimal currencyNum;
33 | try {
34 | currencyNum = new BigDecimal(currencyStr);
35 | }catch (Exception e){
36 | throw new IllegalArgumentException("金额格式错误");
37 | }
38 |
39 | double currencyDoubleValue=currencyNum.doubleValue();
40 | //4限制金额
41 | if (currencyDoubleValue>=1e12) {
42 | throw new IllegalArgumentException("金额过大,不能超过1万亿");
43 | }
44 | if(currencyDoubleValue<0){
45 | throw new IllegalArgumentException("金额必须为正数");
46 | }
47 |
48 | //5保留小数点后两位,四舍五入
49 | currencyNum=currencyNum.setScale(2,BigDecimal.ROUND_HALF_UP);
50 |
51 | //6 处理0元
52 | if (currencyNum.doubleValue() ==0) {
53 | return new String(new char[]{DIGIT_CHARS[0],UNIT_CHARS[0]});
54 | }
55 | //7 转换为字符串,便于取出整数和小数
56 | currencyStr = currencyNum.toPlainString();
57 | int dotPos = currencyStr.lastIndexOf(".");
58 | String integral = currencyStr, decimal = "";
59 | System.out.println(currencyStr);
60 | if (dotPos != -1) {
61 | integral = currencyStr.substring(0, dotPos);
62 | decimal = currencyStr.substring(dotPos + 1,currencyStr.length());
63 | }
64 | //8定义结果字符串数组
65 | StringBuilder result= new StringBuilder();
66 | //9处理整数部分,0.##不处理
67 | if (currencyNum.doubleValue() >= 1) {
68 | int zeroCount = 0;
69 | int pos, numChar;
70 | for (int i = 0; i < integral.length(); i++) {
71 | numChar = integral.charAt(i);
72 | pos = integral.length() - i - 1;
73 | if (numChar != '0') {
74 | //添零
75 | if (zeroCount > 0) {
76 | result.append(DIGIT_CHARS[0]);
77 | zeroCount = 0;
78 | }
79 | //放入对应大写
80 | result.append(DIGIT_CHARS[numChar-'0']);
81 | //放入基数
82 | result.append(RADIX_CHARS[pos % 4]);
83 | } else {
84 | zeroCount++;
85 | }
86 | //添加万亿
87 | if (pos != 0 && pos % 4 == 0 && zeroCount < 4) {
88 | result.append(RADIX_CHARS[pos / 4 + 3]);
89 | }
90 |
91 | }
92 | result.append("元");
93 | }
94 | System.out.println(decimal);
95 | //10处理小数
96 | for (int i = 0; i < decimal.length(); i++) {
97 | result.append(DIGIT_CHARS[decimal.charAt(i)-'0']);
98 | result.append(UNIT_CHARS[i + 1]);
99 | }
100 | //11添加整或正字
101 | if (decimal.length()!= 2) {
102 | result.append(UNIT_CHARS[3]);
103 | }
104 | return result.toString();
105 | }
106 |
107 | public static void main(String[] args) throws Throwable {
108 | String result=convertCurrency("34562323.245543");
109 | System.out.println(result);
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/ThisSystemUtil.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | import java.security.MessageDigest;
4 |
5 | import sun.misc.BASE64Encoder;
6 |
7 | public class ThisSystemUtil {
8 | public static String md5(String s) {
9 | try {
10 | s+="^oa$";
11 | // 确定计算方法
12 | MessageDigest md5 = MessageDigest.getInstance("MD5");
13 | BASE64Encoder base64en = new BASE64Encoder();
14 | // 加密后的字符串
15 | String newstr = base64en.encode(md5.digest(s.getBytes("utf-8")));
16 | return newstr;
17 | } catch (Exception e) {
18 | throw new RuntimeException(e);
19 | }
20 | }
21 |
22 | public static boolean isBlank(String s) {
23 | return s==null||s.trim().length()==0;
24 | }
25 | /**
26 | * 清理字符串前后空格,如果字符串为空白字符串,则返回null
27 | *
28 | * @param s
29 | * @return
30 | */
31 | public static String $(String s,String other) {
32 | if (s != null) {
33 | if ((s = s.trim()).length() == 0)
34 | return other;
35 | else
36 | return s;
37 | }
38 | return other;
39 | }
40 |
41 | /**
42 | * 解析字符串为整数
43 | *
44 | * @param s
45 | * @param defaultInt
46 | * @return
47 | */
48 | public static int parseInt(String s, int defaultInt) {
49 | try {
50 | return Integer.parseInt(s);
51 | } catch (Exception e) {
52 | return defaultInt;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/UserContext.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core;
2 |
3 | import java.time.Instant;
4 | import java.util.Date;
5 |
6 | /**
7 | * 用户上下文
8 | * 包含用户的信息
9 | * @author yizhuoyan@hotmail.com
10 | *
11 | */
12 | public class UserContext {
13 |
14 | private String id;
15 | private String account;
16 | private String name;
17 | private Instant lastLoginTime;
18 | private String lastLoginIp;
19 |
20 |
21 | public String getLastLoginIp() {
22 | return lastLoginIp;
23 | }
24 | public void setLastLoginIp(String lastLoginIp) {
25 | this.lastLoginIp = lastLoginIp;
26 | }
27 |
28 | public String getId() {
29 | return id;
30 | }
31 | public void setId(String id) {
32 | this.id = id;
33 | }
34 | public String getAccount() {
35 | return account;
36 | }
37 | public void setAccount(String account) {
38 | this.account = account;
39 | }
40 | public Instant getLastLoginTime() {
41 | return lastLoginTime;
42 | }
43 | public void setLastLoginTime(Instant lastLoginTime) {
44 | this.lastLoginTime = lastLoginTime;
45 | }
46 | public String getName() {
47 | return name;
48 | }
49 | public void setName(String name) {
50 | this.name = name;
51 | }
52 |
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/core/config/MVCConfig.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.core.config;
2 |
3 | import com.yizhuoyan.teaching.demo.controller.AuthorizationInterceptor;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
7 |
8 | /**
9 | * Created by Administrator on 18/04/17.
10 | */
11 | @Configuration
12 | public class MVCConfig implements WebMvcConfigurer {
13 |
14 | @Override
15 | public void addInterceptors(InterceptorRegistry registry) {
16 | registry.addInterceptor(new AuthorizationInterceptor())
17 | .addPathPatterns("/user/**")
18 | .addPathPatterns("/log/**")
19 | .excludePathPatterns("/user/login.do")
20 | .excludePathPatterns("/user/register.do")
21 | .excludePathPatterns("/user/existAccount.do");
22 | System.out.println(123);
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/dao/SecurityLogDao.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.dao;
2 |
3 | import com.yizhuoyan.teaching.demo.entity.SecurityLogEntity;
4 | import org.springframework.data.domain.Page;
5 | import org.springframework.data.domain.Pageable;
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
8 | import org.springframework.data.jpa.repository.Query;
9 |
10 | /**
11 | * Created by Administrator on 18/04/20.
12 | */
13 | public interface SecurityLogDao extends JpaRepository,JpaSpecificationExecutor{
14 |
15 | @Query(value = "select t from #{#entityName} t where t.ip like %?1% or t.doWhat like %?1%")
16 | Page findByKey(String key,Pageable pageable)throws Exception;
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/dao/UserDao.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.dao;
2 |
3 | import com.yizhuoyan.teaching.demo.entity.UserEntity;
4 | import org.springframework.data.domain.Example;
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | /**
8 | * Created by Administrator on 18/04/17.
9 | */
10 | public interface UserDao extends JpaRepository {
11 |
12 | default UserEntity findByAccount(String account)throws Exception{
13 | UserEntity exp=new UserEntity();
14 | exp.setAccount(account);
15 | return this.findOne(Example.of(exp)).orElse(null);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/entity/SecurityLogEntity.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.entity;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 | import org.hibernate.annotations.GenericGenerator;
5 |
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.Id;
9 | import java.io.Serializable;
10 | import java.time.Instant;
11 |
12 | /**
13 | * Created by Administrator on 18/04/20.
14 | */
15 | @Entity
16 | public class SecurityLogEntity implements Serializable {
17 |
18 | @Id
19 | @GenericGenerator(name = "uuid",strategy = "uuid")
20 | @GeneratedValue(generator = "uuid")
21 | private String id;
22 | //IP
23 | private String ip;
24 | //人物
25 | @JsonProperty("who")
26 | private String occurWho;
27 | //时间
28 | @JsonProperty("when")
29 | private Instant occurWhen=Instant.now();
30 | //经过
31 | private String doWhat;
32 | //结果
33 | private String resultHow;
34 | //原因
35 | private String resultWhy;
36 |
37 | public SecurityLogEntity(String doWhat) {
38 | this.doWhat = doWhat;
39 | }
40 |
41 | public SecurityLogEntity() {
42 | }
43 |
44 | public String getId() {
45 | return id;
46 | }
47 |
48 | public void setId(String id) {
49 | this.id = id;
50 | }
51 |
52 | public String getIp() {
53 | return ip;
54 | }
55 |
56 | public void setIp(String ip) {
57 | this.ip = ip;
58 | }
59 |
60 | public String getOccurWho() {
61 | return occurWho;
62 | }
63 |
64 | public void setOccurWho(String occurWho) {
65 | this.occurWho = occurWho;
66 | }
67 |
68 | public Instant getOccurWhen() {
69 | return occurWhen;
70 | }
71 |
72 | public void setOccurWhen(Instant occurWhen) {
73 | this.occurWhen = occurWhen;
74 | }
75 |
76 | public String getDoWhat() {
77 | return doWhat;
78 | }
79 |
80 | public void setDoWhat(String doWhat) {
81 | this.doWhat = doWhat;
82 | }
83 |
84 | public String getResultHow() {
85 | return resultHow;
86 | }
87 |
88 | public void setResultHow(String resultHow) {
89 | this.resultHow = resultHow;
90 | }
91 |
92 | public String getResultWhy() {
93 | return resultWhy;
94 | }
95 |
96 | public void setResultWhy(String resultWhy) {
97 | this.resultWhy = resultWhy;
98 | }
99 | public void setResultWhy(Exception resultWhy) {
100 | this.resultWhy = resultWhy.toString();
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/entity/UserEntity.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.entity;
2 |
3 | import org.hibernate.annotations.Generated;
4 | import org.hibernate.annotations.GenericGenerator;
5 |
6 | import javax.persistence.Entity;
7 | import javax.persistence.GeneratedValue;
8 | import javax.persistence.GenerationType;
9 | import javax.persistence.Id;
10 | import java.io.Serializable;
11 | import java.time.Instant;
12 | import java.util.Date;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 |
16 | /**
17 | * Created by Administrator on 18/04/16.
18 | */
19 | @Entity
20 | public class UserEntity implements Serializable {
21 | @Id
22 | @GenericGenerator(name = "uuid",strategy = "uuid")
23 | @GeneratedValue(generator = "uuid")
24 | private String id;
25 |
26 | private String account;
27 | private String name;
28 | private Instant lastLoginTime;
29 | private Instant createTime;
30 | private String lastLoginIp;
31 | private String password;
32 |
33 |
34 |
35 | public String getId() {
36 | return id;
37 | }
38 |
39 | public UserEntity setId(String id) {
40 | this.id = id;
41 | return this;
42 | }
43 |
44 | public String getAccount() {
45 | return account;
46 | }
47 |
48 | public UserEntity setAccount(String account) {
49 | this.account = account;
50 | return this;
51 | }
52 |
53 | public String getName() {
54 | return name;
55 | }
56 |
57 | public UserEntity setName(String name) {
58 | this.name = name;
59 | return this;
60 | }
61 |
62 | public Instant getLastLoginTime() {
63 | return lastLoginTime;
64 | }
65 |
66 | public UserEntity setLastLoginTime(Instant lastLoginTime) {
67 | this.lastLoginTime = lastLoginTime;
68 | return this;
69 | }
70 |
71 | public Instant getCreateTime() {
72 | return createTime;
73 | }
74 |
75 | public UserEntity setCreateTime(Instant createTime) {
76 | this.createTime = createTime;
77 | return this;
78 | }
79 |
80 | public String getLastLoginIp() {
81 | return lastLoginIp;
82 | }
83 |
84 | public UserEntity setLastLoginIp(String lastLoginIp) {
85 | this.lastLoginIp = lastLoginIp;
86 | return this;
87 | }
88 |
89 | public String getPassword() {
90 | return password;
91 | }
92 |
93 | public UserEntity setPassword(String password) {
94 | this.password = password;
95 | return this;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/function/LogService.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.function;
2 |
3 | import com.yizhuoyan.teaching.demo.core.PaginationQueryResult;
4 | import com.yizhuoyan.teaching.demo.entity.SecurityLogEntity;
5 |
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by Administrator on 18/04/20.
10 | */
11 | public interface LogService {
12 |
13 | void log(SecurityLogEntity log)throws Exception;
14 |
15 | SecurityLogEntity load(String id)throws Exception;
16 |
17 | PaginationQueryResult find(String key,int pageNo,int pageSize)throws Exception;
18 |
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/function/UserFunction.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.function;
2 |
3 | import com.yizhuoyan.core.UserContext;
4 | import com.yizhuoyan.teaching.demo.controller.ao.ModifyPasswordAo;
5 | import com.yizhuoyan.teaching.demo.controller.ao.UpdateUserAo;
6 | import com.yizhuoyan.teaching.demo.controller.ao.UserAo;
7 | import com.yizhuoyan.teaching.demo.entity.UserEntity;
8 |
9 | import java.util.Map;
10 |
11 | /**
12 | * Created by Administrator on 18/04/17.
13 | */
14 | public interface UserFunction {
15 | UserContext login(String account, String password)throws Exception;
16 |
17 | void registerUser(UserAo u)throws Exception;
18 |
19 | boolean existAccount(String account)throws Exception;
20 |
21 |
22 | UserEntity loadUser(String idOrAccount)throws Exception;
23 |
24 | void updateUser(UpdateUserAo ao)throws Exception;
25 |
26 | void modifyPassword(ModifyPasswordAo ao)throws Exception;
27 |
28 |
29 |
30 |
31 |
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/function/impl/LogServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.function.impl;
2 |
3 | import com.yizhuoyan.teaching.demo.core.PaginationQueryResult;
4 | import com.yizhuoyan.teaching.demo.dao.SecurityLogDao;
5 | import com.yizhuoyan.teaching.demo.entity.SecurityLogEntity;
6 | import com.yizhuoyan.teaching.demo.function.LogService;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.data.domain.Page;
9 | import org.springframework.data.domain.PageRequest;
10 | import org.springframework.data.domain.Pageable;
11 | import org.springframework.data.domain.Sort;
12 | import org.springframework.stereotype.Service;
13 | import org.springframework.transaction.annotation.Transactional;
14 |
15 | import static com.yizhuoyan.teaching.demo.core.ThisSystemUtil.$;
16 |
17 | /**
18 | */
19 | @Transactional
20 | @Service
21 | public class LogServiceImpl implements LogService {
22 |
23 | private final SecurityLogDao dao;
24 | @Autowired
25 | public LogServiceImpl(SecurityLogDao dao) {
26 | this.dao=dao;
27 | }
28 |
29 | @Override
30 | public void log(SecurityLogEntity log) throws Exception {
31 | dao.save(log);
32 | }
33 |
34 | @Override
35 | public SecurityLogEntity load(String id) throws Exception {
36 |
37 | return dao.findById(id).orElse(null);
38 | }
39 |
40 | @Override
41 | public PaginationQueryResult find(String key, int pageNo, int pageSize) throws Exception {
42 | if(pageNo<=0)pageNo=1;
43 | if(pageSize<=0)pageSize=10;
44 | key=$(key,null);
45 | Sort sort=Sort.by(Sort.Direction.DESC,"occurWhen");
46 | Pageable pageable=PageRequest.of(pageNo-1,pageSize,sort);
47 | Page page;
48 | if(key==null){
49 | page=dao.findAll(pageable);
50 | }else{
51 | page=dao.findByKey(key,pageable);
52 | }
53 | PaginationQueryResult result = new PaginationQueryResult<>();
54 |
55 | if(page.hasContent()){
56 |
57 | result.setRows(page.getContent());
58 | }
59 | result.setTotalRows(page.getTotalElements());
60 | result.setPageNo(pageNo);
61 | result.setPageSize(pageSize);
62 |
63 | return result;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/yizhuoyan/teaching/demo/function/impl/UserFunctionImpl.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo.function.impl;
2 |
3 | import com.yizhuoyan.core.PlatformException;
4 | import com.yizhuoyan.core.UserContext;
5 | import com.yizhuoyan.teaching.demo.controller.ao.ModifyPasswordAo;
6 | import com.yizhuoyan.teaching.demo.controller.ao.UpdateUserAo;
7 | import com.yizhuoyan.teaching.demo.controller.ao.UserAo;
8 | import com.yizhuoyan.teaching.demo.dao.UserDao;
9 | import com.yizhuoyan.teaching.demo.entity.UserEntity;
10 | import com.yizhuoyan.teaching.demo.function.UserFunction;
11 | import org.springframework.beans.factory.annotation.Autowired;
12 | import org.springframework.data.domain.Example;
13 | import org.springframework.stereotype.Service;
14 | import org.springframework.transaction.annotation.Transactional;
15 |
16 | import java.time.Instant;
17 |
18 | import java.util.Objects;
19 | import java.util.Optional;
20 | import java.util.regex.Pattern;
21 |
22 | import static com.yizhuoyan.core.AssertThrowUtil.*;
23 |
24 | /**
25 | * Created by Administrator on 18/04/17.
26 | */
27 | @Transactional
28 | @Service
29 | public class UserFunctionImpl implements UserFunction {
30 |
31 | private final UserDao udao;
32 |
33 | @Autowired
34 | public UserFunctionImpl(UserDao udao) {
35 | this.udao=udao;
36 | }
37 |
38 |
39 | public UserContext login(String account, String password)throws Exception{
40 | account = assertNotBlank("账号不能为空", account);
41 | password = assertNotBlank("密码不能为空", password);
42 | UserEntity exp=new UserEntity();
43 | exp.setAccount(account);
44 | UserEntity u = udao.findOne(Example.of(exp)).orElseThrow(()->new PlatformException("账号不存在"));
45 |
46 |
47 | assertEquals("账号或密码不正确", u.getPassword(), password);
48 |
49 |
50 | UserContext uc = new UserContext();
51 | uc.setAccount(account);
52 | uc.setId(u.getId());
53 | uc.setLastLoginIp(u.getLastLoginIp());
54 | uc.setLastLoginTime(u.getLastLoginTime());
55 | uc.setName(u.getName());
56 | //update last login time
57 | u.setLastLoginTime(Instant.now());
58 |
59 | return uc;
60 | }
61 |
62 | @Override
63 | public boolean existAccount(String account) throws Exception {
64 | account = assertNotBlank("账号不能为空", account);
65 | UserEntity exp=new UserEntity();
66 | exp.setAccount(account);
67 | return udao.exists(Example.of(exp));
68 | }
69 |
70 | private static final Pattern ALL_NUMBER = Pattern.compile("\\d+");
71 | private static final Pattern ALL_ALPHABET = Pattern.compile("[a-zA-Z]+");
72 |
73 | @Override
74 | public void registerUser(UserAo ao) throws Exception {
75 | String account = assertNotBlank("账号不能为空", ao.getAccount());
76 | String name = assertNotBlank("名字不能为空", ao.getName());
77 | String password = assertNotBlank("密码不能为空", ao.getPassword());
78 | String passwordConfirm = assertNotBlank("密码确认不能为空", ao.getPasswordConfirm());
79 |
80 | //验证
81 | //account 5-16字符
82 | if (account.length() < 5 || account.length() > 16) {
83 | throw new PlatformException("账号长度必须大于5位小于16位");
84 | }
85 | //name 3-16
86 | if (name.length() < 3 || name.length() > 16) {
87 | throw new PlatformException("名字长度必须大于3位小于16位");
88 | }
89 | //password 6-16字母,数字 不能全数字或者字母
90 | if (password.length() < 6 || password.length() > 16) {
91 | throw new PlatformException("密码长度必须大于6位小于16位");
92 | }
93 |
94 | if (ALL_ALPHABET.matcher(password).matches() || ALL_NUMBER.matcher(password).matches()) {
95 | throw new PlatformException("密码不能全是字母或数字");
96 | }
97 | //两次密码一致
98 | if (!Objects.equals(password, passwordConfirm)) {
99 | throw new PlatformException("两次密码不一致");
100 | }
101 | //账号不能重复
102 | assertFalse("账号已存在",existAccount(account));
103 | UserEntity u = new UserEntity();
104 | u.setAccount(account);
105 | u.setCreateTime(Instant.now());
106 | u.setName(name);
107 | u.setPassword(password);
108 | udao.save(u);
109 | }
110 |
111 | @Override
112 | public UserEntity loadUser(String idOrAccount) throws Exception {
113 | return null;
114 | }
115 |
116 | @Override
117 | public void modifyPassword(ModifyPasswordAo ao) throws Exception {
118 |
119 | String account = assertNotBlank("账号不能为空", ao.getAccount());
120 | String oldPassword = assertNotBlank("旧密码不能为空", ao.getOldPassword());
121 |
122 | String newPassword = assertNotBlank("新密码不能为空", ao.getNewPassword());
123 | String newPasswordConfirm = assertNotBlank("新密码确认不能为空", ao.getNewPasswordConfirm());
124 |
125 | UserEntity u =udao.findByAccount(account);
126 | assertNotNull("账号输入错误", u);
127 | assertEquals("旧密码输入错误", u.getPassword(), oldPassword);
128 | assertEquals("两次新密码不一致", newPassword, newPasswordConfirm);
129 | assertNotEquals("新旧密码不能一样", newPassword, oldPassword);
130 | //password 6-16字母,数字 不能全数字或者字母
131 | if (newPassword.length() < 6 || newPassword.length() > 16) {
132 | throw new PlatformException("密码长度必须大于6位小于16位");
133 | }
134 |
135 | if (ALL_ALPHABET.matcher(newPassword).matches() || ALL_NUMBER.matcher(newPassword).matches()) {
136 | throw new PlatformException("密码不能全是字母或数字");
137 | }
138 |
139 | u.setPassword(newPassword);
140 | }
141 |
142 | @Override
143 | public void updateUser(UpdateUserAo ao) throws Exception {
144 |
145 | String id=assertNotBlank("id不能为空", ao.getId());
146 |
147 | String account = assertNotBlank("账号不能为空", ao.getAccount());
148 |
149 | String name = assertNotBlank("名称不能为空", ao.getName());
150 |
151 |
152 | UserEntity oldUser=udao.findById(id).orElse(null);
153 | assertNotNull("数据不存在",oldUser);
154 | //account
155 | if (!Objects.equals(account, oldUser.getAccount())) {
156 | //account 5-16字符
157 | if (account.length() < 5 || account.length() > 16) {
158 | throw new PlatformException("账号长度必须大于5位小于16位");
159 | }
160 | //账号不能存在
161 | if (existAccount(account)) {
162 | throw new PlatformException("账号已存在");
163 | }
164 |
165 | oldUser.setAccount(account);
166 |
167 | }
168 | //name
169 | if (Objects.equals(name, oldUser.getName())) {
170 | //name 3-16
171 | if (name.length() < 3 || name.length() > 16) {
172 | throw new PlatformException("名字长度必须大于3位小于16位");
173 | }
174 | oldUser.setName(name);
175 |
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yizhuoyan/teaching-project-ajax/157ad8eb939c9ac262e9ea34fbbd31d780bea693/src/main/resources/application.properties
--------------------------------------------------------------------------------
/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
20 |
--------------------------------------------------------------------------------
/src/test/java/com/yizhuoyan/teaching/demo/AjaxApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.yizhuoyan.teaching.demo;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class AjaxApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/模拟web项目API服务数据接口文档.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yizhuoyan/teaching-project-ajax/157ad8eb939c9ac262e9ea34fbbd31d780bea693/模拟web项目API服务数据接口文档.docx
--------------------------------------------------------------------------------