Commit 1521acd5 authored by jianhaijun's avatar jianhaijun

初始文件

parents
/mvnw text eol=lf
*.cmd text eol=crlf
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>weather_forecast</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>my_test</name>
<description>my_test</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 数据库驱动(以MySQL为例) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
<!-- 关键:删除scope标签,默认compile作用域 -->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>3.0.3</version>
<scope>test</scope>
</dependency>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>3.2.0</version>
</dependency>
<!-- Jedis Redis Client -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version>
</dependency>
<!-- FastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JJWT for JWT handling -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.3</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig_bak.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>weather_forecast</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>my_test</name>
<description>my_test</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>
<!-- 数据库驱动(以MySQL为例) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
<!-- 关键:删除scope标签,默认compile作用域 -->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>4.0.1</version>
<scope>test</scope>
</dependency>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Jedis Redis Client -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.0</version>
</dependency>
<!-- FastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.31</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- JJWT for JWT handling -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- Jackson for JSON processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.3</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig_bak.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.example.demo.common;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// 当认证失败时,返回401未授权错误
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
package com.example.demo.common;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtUtil jwtUtil;
public JwtAuthenticationFilter(UserDetailsService userDetailsService, JwtUtil jwtUtil) {
this.userDetailsService = userDetailsService;
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtUtil.getUsernameFromToken(jwtToken);
} catch (Exception e) {
logger.error("Unable to get JWT Token");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwtToken, userDetails.getUsername())) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
chain.doFilter(request, response);
}
}
package com.example.demo.common;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtUtil {
@Value("${jwt.secret:mySecretKeyForJwtTokenGeneration}")
private String secret;
@Value("${jwt.expiration:86400000}")
private Long expiration;
private SecretKey getSigningKey() {
byte[] keyBytes = secret.getBytes(java.nio.charset.StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, username);
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
.compact();
}
public Boolean validateToken(String token, String username) {
final String tokenUsername = getUsernameFromToken(token);
return (tokenUsername.equals(username) && !isTokenExpired(token));
}
}
package com.example.demo.common;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Component
public class RedisUtil {
private static JedisPool jedisPool;
private static boolean isInitialized = false;
static {
try {
// 初始化连接池
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(20); // 最大连接数
config.setMaxIdle(10); // 最大空闲连接数
// 使用 localhost:6379 或通过环境变量配置
String redisHost = System.getProperty("redis.host", "47.121.195.174");
int redisPort = Integer.parseInt(System.getProperty("redis.port", "6379"));
jedisPool = new JedisPool(config, redisHost, redisPort, 2000);
isInitialized = true;
System.out.println("Redis 连接池初始化成功: " + redisHost + ":" + redisPort);
} catch (Exception e) {
System.err.println("Redis 连接失败: " + e.getMessage());
System.err.println("应用将继续运行,但Redis功能不可用");
isInitialized = false;
}
}
/**
* 获取Jedis实例
*/
public static Jedis getJedis() {
if (!isInitialized || jedisPool == null) {
throw new RuntimeException("Redis未初始化或连接失败");
}
return jedisPool.getResource();
}
/**
* 关闭Jedis连接
*/
public static void closeJedis(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
/**
* 设置键值对
*/
public static void set(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
} finally {
closeJedis(jedis);
}
}
/**
* 获取键对应的值
*/
public static String get(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.get(key);
} finally {
closeJedis(jedis);
}
}
/**
* 删除键
*/
public static void del(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
} finally {
closeJedis(jedis);
}
}
/**
* 设置键并设置过期时间(秒)
*/
public static void setex(String key, int seconds, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.setex(key, seconds, value);
} finally {
closeJedis(jedis);
}
}
/**
* 检查键是否存在
*/
public static boolean exists(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.exists(key);
} finally {
closeJedis(jedis);
}
}
/**
* 获取键的过期时间
*/
public static long ttl(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.ttl(key);
} finally {
closeJedis(jedis);
}
}
/**
* 清空数据库
*/
public static void flushDB() {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.flushDB();
} finally {
closeJedis(jedis);
}
}
}
package com.example.demo.common;
import java.io.Serializable;
public class Result<T> implements Serializable{
private int code; // 状态码
private String msg; // 提示信息
private T data; // 泛型承载数据
// 私有构造器(强制使用静态工厂方法)
private Result(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
// 成功响应(带数据)
public static <T> Result<T> success(T data) {
return new Result<>(200, "success", data);
}
// 成功响应(无数据)
public static <T> Result<T> success() {
return success(null);
}
// 失败响应
public static <T> Result<T> error(int code, String msg) {
return new Result<>(code, msg, null);
}
// 便捷失败响应(预定义错误码)
public static <T> Result<T> badRequest(String msg) {
return error(400, msg);
}
// 状态检查
public boolean isSuccess() {
return code == 200;
}
// Getter方法(省略Setter保证不可变性)
public int getCode() { return code; }
public String getMsg() { return msg; }
public T getData() { return data; }
}
package com.example.demo.common;
//import com.example.security.JwtAuthenticationEntryPoint;
//import com.example.security.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public SecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
JwtAuthenticationFilter jwtAuthenticationFilter) {
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
// .requestMatchers("/login/**").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
/**
* 跨域配置类
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 允许所有来源(生产环境建议指定具体域名)
config.addAllowedOriginPattern("*");
// 允许所有请求头
config.addAllowedHeader("*");
// 允许所有请求方法
config.addAllowedMethod("*");
// 允许携带 Cookie
config.setAllowCredentials(true);
// 预检请求的有效期,单位:秒
config.setMaxAge(3600L);
// 暴露的响应头
config.setExposedHeaders(Arrays.asList("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
package com.example.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置类
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(serializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Web MVC 配置类
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 使用后缀模式匹配,支持 URL 末尾的斜杠
configurer.setUseTrailingSlashMatch(true);
}
}
package com.example.demo.controller;
import com.example.demo.common.JwtUtil;
import com.example.demo.entity.User;
import com.example.demo.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserService userService;
private static final long CODE_EXPIRE_TIME = 5; // 验证码过期时间(分钟)
private static final long SEND_INTERVAL = 60; // 发送间隔(秒)
@PostMapping("/send-code")
public ResponseEntity<?> sendVerificationCode(@RequestBody Map<String, String> payload) {
String phoneNumber = payload.get("phoneNumber");
String intervalKey = "interval:" + phoneNumber;
if (Boolean.TRUE.equals(redisTemplate.hasKey(intervalKey))) {
Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "发送过于频繁,请稍后再试");
return ResponseEntity.ok(response);
}
String code = String.format("%06d", new Random().nextInt(999999));
// 实际项目中调用短信服务发送验证码
System.out.println("发送验证码到 " + phoneNumber + ",验证码:" + code);
redisTemplate.opsForValue().set("code:" + phoneNumber, code, CODE_EXPIRE_TIME, TimeUnit.MINUTES);
redisTemplate.opsForValue().set(intervalKey, "1", SEND_INTERVAL, TimeUnit.SECONDS);
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "验证码发送成功");
response.put("code", code);
return ResponseEntity.ok(response);
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody Map<String, String> payload) {
String phoneNumber = payload.get("phoneNumber");
String code = payload.get("code");
String key = "code:" + phoneNumber;
String storedCode = (String) redisTemplate.opsForValue().get(key);
System.out.println(storedCode);
if (storedCode == null || !storedCode.equals(code)) {
Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "验证码错误或已过期");
return ResponseEntity.ok(response);
}
// 验证成功后删除验证码
// redisTemplate.delete(key);
System.out.println("验证码校验成功");
// 方案:直接创建认证对象,跳过密码验证(短信验证码登录)
// 1. 从 UserDetailsService 加载用户信息
org.springframework.security.core.userdetails.UserDetails userDetails =
userDetailsService.loadUserByUsername(phoneNumber);
System.out.println(userDetails);
// User findUser = userService.findByPhone(phoneNumber);
// 2. 创建认证对象(不验证密码,因为已经通过验证码验证了)
Authentication authentication = new UsernamePasswordAuthenticationToken(
userDetails, // 用户信息
null, // 凭证设置为 null,因为使用验证码
userDetails.getAuthorities() // 权限
);
// 这里创建一个用户,存到数据库,如果用户存在,则直接登录,如果没有,则给系统新增一下用户
// 3. 设置认证到 SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
// 4. 生成 JWT Token
String jwt = jwtUtil.generateToken(phoneNumber);
System.out.println("Token 生成成功:" + jwt);
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("token", jwt);
response.put("phoneNumber", phoneNumber);
response.put("message", "登录成功");
return ResponseEntity.ok(response);
}
}
package com.example.demo.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.RedisUtil;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.server.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
@RestController
@RequestMapping("/login")
public class LoginController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
Result<String> successResult;
@Autowired
private UserService userService;
/**
* 发送验证码接口
*/
@PostMapping("/sendCode")
public Object sendCode(@RequestBody String phone) {
try {
// 解析String字符串为JSONObject
JSONObject jsonObject = JSON.parseObject(phone);
String strPhone = (String) jsonObject.get("phone");
//生成随机码
Random random = new Random();
String randomNumber = String.valueOf((random.nextInt(900000) + 100000));
randomNumber = "000000";
// 将验证码存入Redis,设置过期时间为5分钟
RedisUtil.setex(strPhone, 24 * 60 * 60 * 7, randomNumber);
// 这里调用短信服务发送验证码(示例中省略)
// smsService.sendSms(phone, randomNumber)
String getCode = RedisUtil.get(strPhone);
log.info("验证码:" + getCode);
log.info("手机号:" + strPhone);
return Result.success(getCode);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 手机号+验证码登录接口
*/
@PostMapping("/login")
public Object login(@RequestBody Map<String, String> param) {
// 获取存储的验证码
String phone = param.get("phone");
String code = param.get("code");
String getCode = RedisUtil.get(phone);
//比对用户输入的验证码和缓存的验证码是否一致,一致则登录成功
if (code == getCode || code.equals(getCode)) {
//验证码比对成功后进行用户查找,如果用户存在则返回用户信息登录,如果不存在则新建一个用户并返回用户信息
User findUser = userService.findByPhone(phone);
// log.info(String.valueOf(findUser.getPhone() == null));
if (!(findUser == null)){
//生成token并存储到redis
String token = UUID.randomUUID().toString().replace("-", "");
RedisUtil.setex("token" + phone, 24 * 60 * 60 * 7, token);
String getToken = RedisUtil.get("token" + phone);
log.info("登录成功:" + phone);
//删除验证码,先暂时注释掉
// RedisUtil.del(phone);
return Result.success(getToken);
}else{
//如果没有用户则需要创建一个用户再进行登录
while (userService.addUser(phone)){
User newfindUser = userService.findByPhone(phone);
//生成token并存储到redis
String token = UUID.randomUUID().toString().replace("-", "");
RedisUtil.setex("token" + phone, 24 * 60 * 60 * 7, token);
String getToken = RedisUtil.get("token" + phone);
log.info("新建用户并登陆成功:" + newfindUser.getPhone());
//删除验证码,先暂时注释掉
RedisUtil.del(phone);
return Result.success(getToken);
}
}
} else {
log.info(phone + ":手机或验证码错误!");
return "手机或验证码错误!";
}
return Result.success("登录失败!");
}
/**
* 通过客户端缓存的手机+token,当用户进入系统的时候,拿到用户的手机号和token缓存
* 如果手机+token比对成功则直接进入系统,如果对比失败
*/
@PostMapping("/getToken")
public Object getToken(@RequestBody Map<String, String> param) {
// 获取存储的验证码
String phone = param.get("phone");
String token = param.get("token");
log.info(token);
String redisToken = RedisUtil.get("token" + phone);
log.info(redisToken);
if (redisToken == token || redisToken.equals(token)) {
log.info(redisToken);
//封装返回查找结果
successResult = Result.success(redisToken);
} else {
successResult = Result.error(400, "获取token失败,跳转到登录页面");
}
return successResult;
}
}
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/protected")
public class ProtectedController {
@GetMapping("/user-info")
public Map<String, Object> getUserInfo() {
Map<String, Object> response = new HashMap<>();
response.put("message", "这是受保护的用户信息接口");
response.put("data", "用户详细信息...");
return response;
}
@GetMapping("/dashboard")
public Map<String, Object> getDashboard() {
Map<String, Object> response = new HashMap<>();
response.put("message", "这是受保护的仪表盘接口");
response.put("data", "统计数据...");
return response;
}
}
package com.example.demo.controller;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.server.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/users")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
Result<String> successResult;
@Autowired
@Lazy
private UserService userService;
@GetMapping("/demo")
public String demo(@RequestParam("name") String userName, @RequestParam(value = "age", required = false) Integer userAge){
log.info("接口被访问了");
return "测试通过";
}
@PostMapping("/addUser")
public boolean addUser( @RequestBody User user){
User aa = new User();
aa.setName(user.getName());
aa.setAge(user.getAge());
aa.setEmail(user.getEmail());
return userService.save(aa);
}
@PostMapping("/findAllUser")
public Object findAllUser() throws Exception {
Object object = userService.findAll();
//封装返回查找结果
successResult = Result.success(object.toString());
return successResult;
}
}
package com.example.demo.entity;
import lombok.ToString;
import java.util.Date;
@ToString
public class User {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.id
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.name
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String name;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.age
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private Integer age;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.email
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String email;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.create_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private Date createTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.update_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private Date updateTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.phone
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String phone;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info1
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info1;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info2
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info2;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info3
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info3;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info4
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info4;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info5
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info5;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info6
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info6;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.info7
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String info7;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.id
*
* @return the value of user.id
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.id
*
* @param id the value for user.id
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.name
*
* @return the value of user.name
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.name
*
* @param name the value for user.name
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.age
*
* @return the value of user.age
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public Integer getAge() {
return age;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.age
*
* @param age the value for user.age
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setAge(Integer age) {
this.age = age;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.email
*
* @return the value of user.email
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getEmail() {
return email;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.email
*
* @param email the value for user.email
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.create_time
*
* @return the value of user.create_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public Date getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.create_time
*
* @param createTime the value for user.create_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.update_time
*
* @return the value of user.update_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.update_time
*
* @param updateTime the value for user.update_time
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.phone
*
* @return the value of user.phone
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getPhone() {
return phone;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.phone
*
* @param phone the value for user.phone
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info1
*
* @return the value of user.info1
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo1() {
return info1;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info1
*
* @param info1 the value for user.info1
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo1(String info1) {
this.info1 = info1 == null ? null : info1.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info2
*
* @return the value of user.info2
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo2() {
return info2;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info2
*
* @param info2 the value for user.info2
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo2(String info2) {
this.info2 = info2 == null ? null : info2.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info3
*
* @return the value of user.info3
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo3() {
return info3;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info3
*
* @param info3 the value for user.info3
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo3(String info3) {
this.info3 = info3 == null ? null : info3.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info4
*
* @return the value of user.info4
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo4() {
return info4;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info4
*
* @param info4 the value for user.info4
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo4(String info4) {
this.info4 = info4 == null ? null : info4.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info5
*
* @return the value of user.info5
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo5() {
return info5;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info5
*
* @param info5 the value for user.info5
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo5(String info5) {
this.info5 = info5 == null ? null : info5.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info6
*
* @return the value of user.info6
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo6() {
return info6;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info6
*
* @param info6 the value for user.info6
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo6(String info6) {
this.info6 = info6 == null ? null : info6.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.info7
*
* @return the value of user.info7
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getInfo7() {
return info7;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.info7
*
* @param info7 the value for user.info7
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setInfo7(String info7) {
this.info7 = info7 == null ? null : info7.trim();
}
}
\ No newline at end of file
package com.example.demo.entity;
public class UserWithBLOBs extends User {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.ssl_cipher
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private byte[] sslCipher;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.x509_issuer
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private byte[] x509Issuer;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.x509_subject
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private byte[] x509Subject;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.authentication_string
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String authenticationString;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user.User_attributes
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
private String userAttributes;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.ssl_cipher
*
* @return the value of user.ssl_cipher
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public byte[] getSslCipher() {
return sslCipher;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.ssl_cipher
*
* @param sslCipher the value for user.ssl_cipher
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setSslCipher(byte[] sslCipher) {
this.sslCipher = sslCipher;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.x509_issuer
*
* @return the value of user.x509_issuer
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public byte[] getX509Issuer() {
return x509Issuer;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.x509_issuer
*
* @param x509Issuer the value for user.x509_issuer
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setX509Issuer(byte[] x509Issuer) {
this.x509Issuer = x509Issuer;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.x509_subject
*
* @return the value of user.x509_subject
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public byte[] getX509Subject() {
return x509Subject;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.x509_subject
*
* @param x509Subject the value for user.x509_subject
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setX509Subject(byte[] x509Subject) {
this.x509Subject = x509Subject;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.authentication_string
*
* @return the value of user.authentication_string
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getAuthenticationString() {
return authenticationString;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.authentication_string
*
* @param authenticationString the value for user.authentication_string
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setAuthenticationString(String authenticationString) {
this.authenticationString = authenticationString == null ? null : authenticationString.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user.User_attributes
*
* @return the value of user.User_attributes
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public String getUserAttributes() {
return userAttributes;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user.User_attributes
*
* @param userAttributes the value for user.User_attributes
*
* @mbggenerated Tue Mar 24 14:47:39 CST 2026
*/
public void setUserAttributes(String userAttributes) {
this.userAttributes = userAttributes == null ? null : userAttributes.trim();
}
}
\ No newline at end of file
package com.example.demo.entityMapper;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
@Data
@ToString
public class Users {
private Integer id;
private String name;
private Integer age;
private String email;
private Date createTime;
private Date updateTime;
private String phone;
private String orderId;
}
\ No newline at end of file
package com.example.demo.mapper;
import com.example.demo.entity.User;
import java.util.List;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Select("SELECT * FROM user WHERE phone = #{phone}")
User findByPhone(String phone);
@Insert("INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
@Update("UPDATE user SET name=#{name}, age=#{age}, email=#{email} WHERE id=#{id}")
int update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteById(Long id);
@Insert("INSERT INTO user(name,phone) VALUES(#{name},#{phone})")
@Options(useGeneratedKeys = true, keyProperty = "id")
Boolean addUser(User user);
}
package com.example.demo.server;
import com.example.demo.entity.User;
import java.util.List;
public interface UserService {
Object findAll();
User findById(Long id);
boolean save(User user);
boolean update(User user);
boolean deleteById(Long id);
User findByPhone(String phone);
boolean addUser(String phone);
}
\ No newline at end of file
package com.example.demo.serviceImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Collections;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 模拟用户信息,实际项目中应从数据库获取
return org.springframework.security.core.userdetails.User.builder()
.username(username)
.password("$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG") // 123456加密后
.authorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))
.accountExpired(false)
.accountLocked(false)
.credentialsExpired(false)
.disabled(false)
.build();
}
}
package com.example.demo.serviceImpl;
import com.example.demo.controller.UserController;
import com.example.demo.entity.User;
import com.example.demo.entityMapper.Users;
import com.example.demo.mapper.UserMapper;
import com.example.demo.server.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserServiceImpl implements UserService {
@Autowired
@Lazy
private UserMapper userMapper;
private static final Logger log = LoggerFactory.getLogger(UserController.class);
@Override
public Object findAll() {
List<User> findAlls = userMapper.findAll();
List<Object> findever = new ArrayList<>();
Map<String,String> map1 = new HashMap<>();
for (User findAll : findAlls) {
Map<String,String> map = new HashMap<>();
map.put("id",findAll.getId().toString());
map.put("name",findAll.getName().toString());
map.put("Email",findAll.getEmail().toString());
map.put("phone",findAll.getPhone().toString());
map.put("age",findAll.getAge().toString());
map.put("orderId", String.valueOf(System.currentTimeMillis())+((int) (Math.random() * 9000) + 1000));
findever.add(map);
}
return findever;
}
@Override
public User findById(Long id) {
return null;
}
@Override
public boolean deleteById(Long id) {
return false;
}
@Override
public User findByPhone(String phone) {
User user = userMapper.findByPhone(phone);
return user;
}
@Override
public boolean addUser(String phone) {
User user = new User();
user.setName("张三");
user.setPhone(phone);
return userMapper.addUser(user);
}
@Override
public boolean update(User user) {
return false;
}
@Override
public boolean save(User user) {
try {
userMapper.insert(user);
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
\ No newline at end of file
package com.example.my_test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(scanBasePackages = {"com.example"})
@ComponentScan(basePackages = {"com.example"})
@MapperScan("com.example.demo.mapper")
public class MyTestApplication {
public static void main(String[] args) {
// 设置Redis连接参数(可选,通过-D参数覆盖)
// java -Dredis.host=localhost -Dredis.port=6379 -jar app.jar
SpringApplication.run(MyTestApplication.class, args);
}
}
package com.example.my_test;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
public class TestDriver {
@Autowired
@Lazy
public static UserMapper userMapper;
public static void main(String[] args) {
System.out.println(userMapper.findAll());
}
}
spring:
application:
name: my_test
datasource:
url: jdbc:mysql://47.121.195.174:3306/weatherdata?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: Aq1234554321!
driver-class-name: com.mysql.cj.jdbc.Driver
# 适配2核2G服务器的轻量化连接池配置
hikari:
maximum-pool-size: 5
minimum-idle: 1
idle-timeout: 30000
max-lifetime: 1800000
# MyBatis相关配置
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.example.demo.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启SQL日志输出
# MVC配置:处理尾部斜杠
mvc:
pathmatch:
matching-strategy: ant_path_matcher
# Redis配置
data:
redis:
host: 47.121.195.174
port: 6379
# SpringBoot应用端口配置
server:
port: 8080
address: 0.0.0.0
jwt:
secret: mySuperSecretKeyForJWTTokenGenerationThatIsLongEnoughToMeetSecurityRequirements123456
expiration: 604800000
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库连接配置 -->
<context id="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://47.121.195.174:3306/weatherdata?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"
userId="root"
password="Aq1234554321!">
</jdbcConnection>
<!-- 实体类生成配置 -->
<javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- Mapper接口生成配置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- Mapper实现类生成配置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mapper" targetProject="src/main/java"/>
<!-- 表配置:对应数据库中的user表 -->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"/>
</context>
</generatorConfiguration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库连接配置 -->
<context id="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://47.121.195.174:3306/weatherdata?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"
userId="root"
password="Aq1234554321!">
</jdbcConnection>
<!-- 实体类生成配置 -->
<javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- Mapper接口生成配置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- Mapper实现类生成配置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mapper" targetProject="src/main/java"/>
<!-- 数据库表映射配置 -->
<!-- <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"/>-->
<table tableName="user" domainObjectName="User">
<!-- 关闭Example类生成 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
<!-- 关闭BLOB字段拆分 -->
<columnOverride column="avatar" javaType="byte[]"/>
</table>
</context>
</generatorConfiguration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="info1" jdbcType="VARCHAR" property="info1" />
<result column="info2" jdbcType="VARCHAR" property="info2" />
<result column="info3" jdbcType="VARCHAR" property="info3" />
<result column="info4" jdbcType="VARCHAR" property="info4" />
<result column="info5" jdbcType="VARCHAR" property="info5" />
<result column="info6" jdbcType="VARCHAR" property="info6" />
<result column="info7" jdbcType="VARCHAR" property="info7" />
</resultMap>
<sql id="Example_Where_Clause">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
id, name, age, email, create_time, update_time, phone, info1, info2, info3, info4,
info5, info6, info7
</sql>
<select id="selectByExample" parameterType="com.example.demo.entity.UserExample" resultMap="BaseResultMap">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.example.demo.entity.UserExample">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
delete from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.example.demo.entity.User">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user (name, age, email,
create_time, update_time, phone,
info1, info2, info3,
info4, info5, info6,
info7)
values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{email,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{phone,jdbcType=VARCHAR},
#{info1,jdbcType=VARCHAR}, #{info2,jdbcType=VARCHAR}, #{info3,jdbcType=VARCHAR},
#{info4,jdbcType=VARCHAR}, #{info5,jdbcType=VARCHAR}, #{info6,jdbcType=VARCHAR},
#{info7,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.example.demo.entity.User">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="age != null">
age,
</if>
<if test="email != null">
email,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="phone != null">
phone,
</if>
<if test="info1 != null">
info1,
</if>
<if test="info2 != null">
info2,
</if>
<if test="info3 != null">
info3,
</if>
<if test="info4 != null">
info4,
</if>
<if test="info5 != null">
info5,
</if>
<if test="info6 != null">
info6,
</if>
<if test="info7 != null">
info7,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
<if test="info1 != null">
#{info1,jdbcType=VARCHAR},
</if>
<if test="info2 != null">
#{info2,jdbcType=VARCHAR},
</if>
<if test="info3 != null">
#{info3,jdbcType=VARCHAR},
</if>
<if test="info4 != null">
#{info4,jdbcType=VARCHAR},
</if>
<if test="info5 != null">
#{info5,jdbcType=VARCHAR},
</if>
<if test="info6 != null">
#{info6,jdbcType=VARCHAR},
</if>
<if test="info7 != null">
#{info7,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.example.demo.entity.UserExample" resultType="java.lang.Integer">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
select count(*) from user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
update user
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name != null">
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.age != null">
age = #{record.age,jdbcType=INTEGER},
</if>
<if test="record.email != null">
email = #{record.email,jdbcType=VARCHAR},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=TIMESTAMP},
</if>
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=TIMESTAMP},
</if>
<if test="record.phone != null">
phone = #{record.phone,jdbcType=VARCHAR},
</if>
<if test="record.info1 != null">
info1 = #{record.info1,jdbcType=VARCHAR},
</if>
<if test="record.info2 != null">
info2 = #{record.info2,jdbcType=VARCHAR},
</if>
<if test="record.info3 != null">
info3 = #{record.info3,jdbcType=VARCHAR},
</if>
<if test="record.info4 != null">
info4 = #{record.info4,jdbcType=VARCHAR},
</if>
<if test="record.info5 != null">
info5 = #{record.info5,jdbcType=VARCHAR},
</if>
<if test="record.info6 != null">
info6 = #{record.info6,jdbcType=VARCHAR},
</if>
<if test="record.info7 != null">
info7 = #{record.info7,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
update user
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
age = #{record.age,jdbcType=INTEGER},
email = #{record.email,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=TIMESTAMP},
update_time = #{record.updateTime,jdbcType=TIMESTAMP},
phone = #{record.phone,jdbcType=VARCHAR},
info1 = #{record.info1,jdbcType=VARCHAR},
info2 = #{record.info2,jdbcType=VARCHAR},
info3 = #{record.info3,jdbcType=VARCHAR},
info4 = #{record.info4,jdbcType=VARCHAR},
info5 = #{record.info5,jdbcType=VARCHAR},
info6 = #{record.info6,jdbcType=VARCHAR},
info7 = #{record.info7,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.example.demo.entity.User">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
update user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="info1 != null">
info1 = #{info1,jdbcType=VARCHAR},
</if>
<if test="info2 != null">
info2 = #{info2,jdbcType=VARCHAR},
</if>
<if test="info3 != null">
info3 = #{info3,jdbcType=VARCHAR},
</if>
<if test="info4 != null">
info4 = #{info4,jdbcType=VARCHAR},
</if>
<if test="info5 != null">
info5 = #{info5,jdbcType=VARCHAR},
</if>
<if test="info6 != null">
info6 = #{info6,jdbcType=VARCHAR},
</if>
<if test="info7 != null">
info7 = #{info7,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.demo.entity.User">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Mar 24 14:47:39 CST 2026.
-->
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
email = #{email,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
phone = #{phone,jdbcType=VARCHAR},
info1 = #{info1,jdbcType=VARCHAR},
info2 = #{info2,jdbcType=VARCHAR},
info3 = #{info3,jdbcType=VARCHAR},
info4 = #{info4,jdbcType=VARCHAR},
info5 = #{info5,jdbcType=VARCHAR},
info6 = #{info6,jdbcType=VARCHAR},
info7 = #{info7,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 数据库连接配置 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://47.121.195.174:3306/weatherdata?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="Aq1234554321!"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件路径配置 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment