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
This diff is collapsed.
<# : 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;
}
}
This diff is collapsed.
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>
This diff is collapsed.
<?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