SpringBoot整合MybatisPlus, Redis,hikari ,swagger2 帶配置寫法
阿新 • • 發佈:2019-01-28
工具idea , 模組化專案搭建
1:先建立一個project 刪掉其中的src等多餘目錄 ,留一個 pom.xml
pom.xml 如下:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.text</groupId> <artifactId>demo</artifactId> <version>1.0-SNAPSHOT</version> <!-- 定義版本--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> </project>
2:右鍵專案,建立一個module 專案 【demoAdmin】 , 注:建立專案後,外層pom會多個 modules
此模組 pom.xml 如下:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>demo</artifactId> <groupId>com.text</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>demoAdmin</artifactId> <dependencies> <!-- 支援web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--get set data 等外掛 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--mybatis-plus 核心包 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.0.5</version> </dependency> <!-- mybatis-plus velocity 模板引擎, 預設--> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency> <!-- 連線池 6以上版本在連線屬性中要加上[ &serverTimezone=Asia/Shanghai ] 6.0 版本以上必須配置此引數--> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.0.4.RELEASE</version> </dependency> <!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <!-- 自定義jar ,名字隨便起,儘量統一規範(此處防止打包時,打不進去第三方jar)--> <!-- <dependency> <groupId>custom</groupId> <artifactId>customSelf</artifactId> <version>1.0.0</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/resources/lib/custom-3.3.1.jar</systemPath> </dependency>--> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <!-- 將jar統一打進lib目錄下 --> <directory>src/main/resources/lib</directory> <targetPath>BOOT-INF/lib</targetPath> </resource> </resources> <!-- 配置打包及打包後的專案存放路徑 outputDirectory --> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <finalName>${project.name}</finalName> <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments> <outputDirectory>E:/compose/demoJar</outputDirectory> </configuration> </plugin> </plugins> </build> </project>
3:程式碼寫法 專案結構如下圖:
包檔案解釋:
common: 公共類配置 config: 配置檔案 config.interceptor: 攔截器配置 controller: 控制器 dao: dao層 model.dto: 入參類 model.entity: 實體類 model.vo : 出參類 service : 介面類 service.impl: 介面實現類 shiro: 許可權類 util: 工具類 AdminApplication.class : 啟動入口
3-1:resources 配置
application.yml 如下圖:
# 伺服器配置 以自己的配置為主
server:
port: 8070
servlet:
context-path: /admin
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.demo.model.entity
logging:
config: classpath:logback-spring.xml
spring:
profiles:
#active: main # 正式環境
active: demo #測試環境
application-demo.yml 如下圖:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 15
max-lifetime: 180000
idle-timeout: 60000
connection-timeout: 20000
minimum-idle: 5
redis:
port: 6379
host: 127.0.0.1
password:123456
banner.txt 如下圖:
${AnsiColor.BRIGHT_YELLOW}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 Admin 永不宕機 永無BUG //
////////////////////////////////////////////////////////////////////
${AnsiColor.BRIGHT_RED}
Application Version: ${application.version}${application.formatted-version}
Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}
logback-spring.xml 如下圖:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="false">
<springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue="home"/>
<property name="LOG_HOME" value="/home/demo/logs/admin" />
<!-- 控制檯輸出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符-->
<pattern>%yellow(%d{yyyy-MM-dd HH:mm:ss}) [%-5level] [ %boldMagenta(%logger{50}) ] - %cyan(%msg%n)
</pattern>
</encoder>
</appender>
<!-- 按照每天生成日誌檔案 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/admin.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日誌檔案輸出的檔名-->
<fileNamePattern>${LOG_HOME}/admin.log.%d{yyyy-MM-dd}.part%i.gz</fileNamePattern>
<!-- 同時按照大小和日期分割日誌檔案 -->
<maxFileSize>2GB</maxFileSize>
<maxHistory>10</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.demo.dao" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</logger>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
3-2 common 包結構class如下圖:
類檔案解釋:
ApiCommonController: 自定義父類 ,封裝了自定義異常監控
BaseController: 自定義父類 ,封裝了返回結果物件,獲取ip
BaseDto: 分頁類,用於傳參物件繼承使用
BusinessException: 自定義異常
CodeGeneration: mybatisPlus 程式碼生成器
Result: 返回結果物件
ApiCommonController.jar 程式碼如下
package com.demo.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@Slf4j
public class ApiCommonController extends BaseController {
/**
* 丟擲自定義BusinessException異常
*/
@ExceptionHandler({BusinessException.class})
@ResponseBody
public Result business(BusinessException ex) {
log.info(ex.toString());
return new Result(Result.ERROR,ex.getMessage());
}
protected void check(String code ,Object obj){
if (obj==null||obj.toString().trim().equals("null")||obj.toString().trim().length()==0) {
throw new BusinessException("引數[" +code+ "]不能為空");
}
}
}
BaseController.java 如下圖:
package com.demo.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
@Slf4j
public class BaseController {
@Autowired
protected HttpServletRequest request;
/**
* 返回成功結果集
*/
protected Result ajaxDoneSuccess(Object data) {
return new Result(Result.SUCCESS, Result.SUCCESSMSG, data);
}
protected Result ajaxDoneSuccess(Object data,Integer total) {
return new Result(Result.SUCCESS, Result.SUCCESSMSG, data,total);
}
/**
* 返回成功結果
*/
protected Result ajaxDoneSuccess(String message) {
return new Result(Result.SUCCESS, message);
}
/**
* 返回成功結果和物件
*/
protected Result ajaxDoneSuccess(String message,Object data) {
return new Result(Result.SUCCESS, message,data);
}
/**
* 返回失敗結果集
*/
protected Result ajaxDoneError(String message) {
return new Result(Result.ERROR, message);
}
/**
* 獲取ip
*/
protected String getRealIp(){
String ip = request.getHeader("X-Real-IP");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("x-forwarded-for");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
BaseDto.java 程式碼如下圖:
package com.demo.common;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class BaseDto {
@ApiModelProperty(value = "當前第幾頁")
private Integer pageIndex = 1;//當前第幾頁
@ApiModelProperty(value = "每頁顯示數")
private Integer pageSize = 10; //每頁顯示數
@ApiModelProperty(value = "開始時間 -查詢")
private String beginTime;
@ApiModelProperty(value = "結束時間 -查詢")
private String endTime;//結束時間 -查詢
}
BusinessException.java 如下圖:
package com.demo.common;
/**
* 自定義異常
*/
public class BusinessException extends RuntimeException {
public BusinessException(String msg){
super(msg);
}
}
Result.java 如下圖:
package com.demo.common;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class Result {
public static final int SUCCESS = 200;
public static final int ERROR= 500;
public static final String SUCCESSMSG = "成功";
@ApiModelProperty(value = "狀態碼 200")
private int code = 0;
@ApiModelProperty(value = "說明資訊")
private String msg = "";
@ApiModelProperty(value = "資料")
private Object data;
@ApiModelProperty(value = "資料總條數")
private Integer total=0; //條數
public Result(int code,String msg){
this.code=code;
this.msg=msg;
}
public Result(int code,String msg,Object data){
this.code=code;
this.msg=msg;
this.data=data;
}
public Result(int code,String msg,Object data ,Integer total){
this.code=code;
this.msg=msg;
this.data=data;
this.total=total;
}
}
CodeGeneration.java 程式碼生成器 如下圖:
package com.demo.common;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class CodeGeneration {
/**
*
* @Title: main
* @Description: 檔案生成器 執行main方法即可
* @param args
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全域性配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("E://generation//temp");
gc.setFileOverride(true);
gc.setActiveRecord(false);// 不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);// XML 二級快取
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor("ccm");// 作者
// 自定義檔案命名,注意 %s 會自動填充表實體屬性!
//gc.setControllerName("%sAction");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sDao");
gc.setXmlName("%sMapper");
mpg.setGlobalConfig(gc);
// 資料來源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//strategy.setTablePrefix(new String[] { "sys_" });// 此處可以修改為您的表字首
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
//strategy.setInclude(new String[] { "sys_user" }); // 需要生成的表
strategy.setSuperServiceClass(null);
strategy.setSuperServiceImplClass(null);
strategy.setSuperMapperClass(null);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.demo");
//pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.serviceImpl");
pc.setMapper("dao");
pc.setEntity("model.entity");
pc.setXml("xml");
mpg.setPackageInfo(pc);
// 執行生成
mpg.execute();
}
}
3-3 config 包結構class如下圖:
類檔案解釋:
HandlerInterceptorConfig: 攔截器
MyHandlerInterceptorConfig: 自定義攔截
corsFilter: 跨域
MybatisPlusConfig: MybatisPlus配置
RedisConfig: Redis配置
SwaggerConfig: Swagger2配置
HandlerInterceptorConfig.java 程式碼如下:
package com.demo.config.interceptor;
import com.demo.common.BusinessException;
import com.demo.config.RedisConfig;
import com.demo.shiro.ShiroAdmin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class HandlerInterceptorConfig implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HttpSession session= request.getSession();
String keyName=RedisConfig.reids_prefix+session.getId();
ShiroAdmin shiroAdmin= (ShiroAdmin) redisTemplate.opsForValue().get(keyName);
if (shiroAdmin==null){
throw new BusinessException("當前賬號未登入,請先登陸");
}
String token = request.getHeader("token");
if (token == null || token.trim().length() == 0) {
throw new BusinessException("token 禁止為空");
}
if (!shiroAdmin.getToken().equals(token)) {
throw new BusinessException("賬號在其他地方登入,請重新登入");
}
shiroAdmin.setSessionId(" 被攔截 當前會話:"+session.getId());
request.getSession().setAttribute("shiroAdmin",shiroAdmin);
redisTemplate.expire(keyName,2,TimeUnit.HOURS);
return true;
}
}
MyHandlerInterceptorConfig.java 程式碼如下:
package com.demo.config.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyHandlerInterceptorConfig implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor handlerInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(handlerInterceptor).addPathPatterns("/**")
.excludePathPatterns("/login/**")
.excludePathPatterns("/*.html")
.excludePathPatterns("/webjars/**")
.excludePathPatterns("//swagger-resources/**");
}
}
MybatisPlusConfig.java 程式碼如下:
package com.demo.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan({"com.demo.dao"})
public class MybatisPlusConfig {
/**
* 效能優化 複雜查詢可能會報錯 建議關掉
* @return
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/*<!-- SQL 執行效能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->*/
performanceInterceptor.setMaxTime(1000);
/*<!--SQL是否格式化 預設false-->*/
performanceInterceptor.setFormat(false);
return performanceInterceptor;
}
/**
* 分頁外掛
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
RedisConfig.java 程式碼如下 :
package com.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
public final static String reids_prefix="demo_admin_" ; //redis字首
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
ObjectMapper mapper = new ObjectMapper();
template.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(預設使用JDK的序列化方式)
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
SwaggerConfig.java 程式碼如下
package com.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("token").description("登入校驗token")//name表示物件名稱,description表示描述
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();//required表示是否必填,defaultvalue表示預設值
pars.add(ticketPar.build());//新增完此處一定要把下邊的帶***的也加上否則不生效
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);//************把訊息頭新增
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("測試介面")
.description("admin端介面")
.termsOfServiceUrl("none")
.version("1.0").build();
}
}
3-4 shiro包結構class如下圖:
ShiroAdmin.java 封裝物件 程式碼如下:
package com.demo.shiro;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 登陸物件
*/
@Data
public class ShiroAdmin {
@ApiModelProperty(value = "管理員id")
private Integer adminId;
@ApiModelProperty(value = "token")
private String token;
@ApiModelProperty(value = "登陸id")
private String loginCode;
@ApiModelProperty(value = "許可權id")
private Integer roleId;
@ApiModelProperty(value = "手機號")
private String phone;
@ApiModelProperty(value = "會話id")
private String sessionId;
}
AuthManager.java 獲取當前登陸的物件
package com.demo.shiro;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class AuthManager {
public static ShiroAdmin getShiroAdmin() {
return (ShiroAdmin)getSession().getAttribute("shiroAdmin");
}
public static String getSessionId(){
return getSession().getId();
}
public static HttpSession getSession(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request.getSession();
}
}
3-5 : 控制器 LoginController.java 程式碼如下s
package com.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.common.ApiCommonController;
import com.demo.common.Result;
import com.demo.config.RedisConfig;
import com.demo.model.dto.LoginDto;
import com.demo.model.entity.TSysAdmin;
import com.demo.service.TSysAdminService;
import com.demo.shiro.AuthManager;
import com.demo.shiro.ShiroAdmin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/login")
@Api(description = "登陸註冊")
public class LoginController extends ApiCommonController {
@Autowired
private TSysAdminService tSysAdminService;
@Autowired
private RedisTemplate redisTemplate;
@ApiOperation(value = "登陸", response = String.class)
@PostMapping("/loginDo")
public Result loginDo(@RequestBody LoginDto dto){
if (AuthManager.getSessionId()==null){
return ajaxDoneError("登陸異常,錯誤程式碼-10000");
}
TSysAdmin tSystemAdmin=tSysAdminService.getOne(new QueryWrapper<TSysAdmin>().eq("login_code",dto.getLoginCode()).eq("pwd",dto.getPwd()));
if (tSystemAdmin==null){
return ajaxDoneError("賬號或密碼有誤");
}
System.out.println("--------------------------------------");
ShiroAdmin shiroAdmin=new ShiroAdmin();
shiroAdmin.setAdminId(tSystemAdmin.getId());
shiroAdmin.setLoginCode(tSystemAdmin.getLoginCode());
shiroAdmin.setPhone(tSystemAdmin.getPhone());
shiroAdmin.setRoleId(tSystemAdmin.getRoleId());
shiroAdmin.setSessionId(AuthManager.getSessionId());
shiroAdmin.setToken(RandomStringUtils.randomAlphanumeric(24)+tSystemAdmin.getId());
String keyName=RedisConfig.reids_prefix+shiroAdmin.getSessionId();
redisTemplate.opsForValue().set(keyName,shiroAdmin,2,TimeUnit.HOURS);
return ajaxDoneSuccess("登陸成功 good",shiroAdmin.getToken());
}
}
3-6 : 入口類 AdminApplication.java
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement //開啟事務
@ComponentScan(basePackages = {"com.demo.*"})
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class,args);
}
}
4: 專案配置完成 專案完整介面入下圖:
**
下載後 1:將CodeGeneration.java檔案中的資料庫連線改成實際的
2:將配置檔案中的資料庫,redis 改成實際的