PageHelper

  1. <!-- pageHelper分页插件 -->
  2. <dependency>
  3. <groupId>com.github.pagehelper</groupId>
  4. <artifactId>pagehelper-spring-boot-starter</artifactId>
  5. <version>1.4.2</version>
  6. </dependency>
  1. # pagehelper分页插件配置
  2. # 配置分页数据库
  3. pagehelper.helper-dialect=mysql
  4. #启用合理化,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页
  5. pagehelper.reasonable=true
  6. #为了支持startPage(Object params)方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值
  7. # 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值
  8. # 默认值为pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero
  9. pagehelper.params=count=countSql
  10. #支持通过 Mapper 接口参数来传递分页参数,默认值false
  11. # 分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页
  12. pagehelper.supportMethodsArguments=true
  13. #如果 pageSize=0 就会查询出全部的结果(相当于没有执行分页查询)
  14. pagehelper.page-size-zero=true
  1. // 查询mapper执行前赋值
  2. PageHelper.startPage(1,20);

ES

1、添加maven依赖

  1. <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch -->
  2. <dependency>
  3. <groupId>org.springframework.data</groupId>
  4. <artifactId>spring-data-elasticsearch</artifactId>
  5. <version>4.3.4</version>
  6. </dependency>

2、设置springboot中ES的版本

  1. <!-- 需要在项目中引入springboot parent包来覆盖es版本 -->
  2. <parent>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-parent</artifactId>
  5. <version>2.5.0</version>
  6. <relativePath/>
  7. </parent>
  8. <!-- 覆盖springboot默认es版本 -->
  9. <elasticsearch.version>7.13.0</elasticsearch.version>

3、添加es配置文件

  1. spring:
  2. data:
  3. elasticsearch:
  4. client:
  5. reactive:
  6. endpoints: 172.16.88.128:9200
  7. username:
  8. password:
  9. connection-timeout: 5000
  10. socket-timeout: 60000

4、添加es client配置

  1. /**
  2. * 初始化 es客户端 bean 7.13.0
  3. * @return
  4. */
  5. @Override
  6. @Bean
  7. public RestHighLevelClient elasticsearchClient() {
  8. final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
  9. .connectedTo(endpoints)
  10. .withConnectTimeout(connectTimeout)
  11. .withSocketTimeout(socketTimeout)
  12. .withBasicAuth(username, password)
  13. .build();
  14. log.info("==============初始化ES客户端连接" + endpoints + "=================");
  15. return RestClients.create(clientConfiguration).rest();
  16. }

继承 ElasticsearchRepository 即可使用通用api

  1. package com.csj.demo.business.repository;
  2. import com.csj.demo.business.POJO.DO.User;
  3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  4. /**
  5. * @Desc : 用户es操作类
  6. * @Author : chen
  7. * @Date : 2022/4/22 17:11
  8. */
  9. public interface UserRepository extends ElasticsearchRepository<User, Long> {
  10. }

TK-Mybatis-Mapper

  1. <!--通用Mapper-->
  2. <dependency>
  3. <groupId>tk.mybatis</groupId>
  4. <artifactId>mapper-spring-boot-starter</artifactId>
  5. <version>4.2.0</version>
  6. </dependency>
  1. # tkmapper 使用
  2. mapper.identity=MYSQL
  3. mapper.not-empty=true
  1. package com.csj.demo.business.component;
  2. import tk.mybatis.mapper.common.Mapper;
  3. import tk.mybatis.mapper.common.MySqlMapper;
  4. /**
  5. * @Desc : basemapper
  6. * @Author : chen
  7. * @Date : 2022/4/24 15:37
  8. */
  9. public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
  10. }
  1. // 使用过程中继承mymapper即可
  2. public interface UserMapper extends MyMapper<User> {
  3. }

mybatis

  1. # mybatis配置
  2. # mybatis全局配置
  3. mybatis.config-location:classpath:mybatis-config.xml
  4. # resultType 可以只写类的全限定名
  5. mybatis.type-aliases-package=com.csj.demo.business.POJO.DO
  6. # xml文件目录
  7. mybatis.mapper-locations=classpath:mapper/*Mapper.xml
  1. <!-- mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>2.2.2</version>
  6. </dependency>

Druid

  1. spring:
  2. # 设置数据源
  3. datasource:
  4. url: jdbc:mysql://172.16.88.128:3306/DB01?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
  5. username: root
  6. password: 123456
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. druid:
  10. # 初始化大小,最小,最大活跃数
  11. initial-size: 3
  12. min-idle: 3
  13. max-active: 20
  14. # 配置获取连接等待超时的时间,单位是毫秒
  15. max-wait: 60000
  16. # asyncInit是1.1.4中新增加的配置,如果有initialSize数量较多时,打开会加快应用启动时间
  17. async-init: true
  18. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  19. time-between-eviction-runs-millis: 60000
  20. # 配置一个连接在池中最小生存的时间,单位是毫秒
  21. min-evictable-idle-time-millis: 30000
  22. max-evictable-idle-time-millis: 300000
  23. # 用于检查连接的语句
  24. validation-query: SELECT 1
  25. test-while-idle: true
  26. # 申请连接时执行validationQuery检测连接是否有效,会影响性能
  27. test-on-borrow: false
  28. # 归还连接时执行validationQuery检测连接是否有效
  29. test-on-return: false
  30. # 打开缓存PSCache,并且指定每个连接上PSCache的大小,mysql作用不大建议关闭,oracle开启效果好
  31. pool-prepared-statements: false
  32. max-pool-prepared-statement-per-connection-size: -1
  33. max-open-prepared-statements: -1
  34. #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,slf4j(用log4j需要额外导入依赖,版本不同,这里也可以去掉slf4j)
  35. filters: stat,wall,slf4j
  36. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  37. connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=true
  38. # 配置监控服务器
  39. stat-view-servlet:
  40. enabled: true
  41. url-pattern: /druid/*
  42. # 是否可重置数据
  43. reset-enable: false
  44. login-username: druid
  45. login-password: druid123
  46. web-stat-filter:
  47. enabled: true
  48. url-pattern: /*
  49. exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,*.woff2
  50. session-stat-enable: true
  51. session-stat-max-count: 10
  52. filter:
  53. slf4j:
  54. enabled: true
  55. statement-create-after-log-enabled: false
  56. statement-close-after-log-enabled: false
  57. result-set-open-after-log-enabled: false
  58. result-set-close-after-log-enabled: false
  1. //单数据源时可忽略,springboot会自动配置
  2. @Value("${spring.datasource.url}")
  3. private String url;
  4. @Value("${spring.datasource.username}")
  5. private String username;
  6. @Value("${spring.datasource.password}")
  7. private String password;
  8. @Value("${spring.datasource.driver-class-name}")
  9. private String driverClassName;
  10. @Value("${spring.datasource.initial-size}")
  11. private int initialSize;
  12. @Value("${spring.datasource.min-idle}")
  13. private int minIdle;
  14. @Value("${spring.datasource.max-active}")
  15. private int maxActive;
  16. @Value("${spring.datasource.max-wait}")
  17. private int maxWait;
  18. @Value("${spring.datasource.time-between-eviction-runs-millis}")
  19. private int timeBetweenEvictionRunsMillis;
  20. @Value("${spring.datasource.min-evictable-idle-time-millis}")
  21. private int minEvictableIdleTimeMillis;
  22. @Value("${spring.datasource.max-evictable-idle-time-millis}")
  23. private int maxEvictableIdleTimeMillis;
  24. @Value("${spring.datasource.pool-prepared-statements}")
  25. private boolean poolPreparedStatements;
  26. @Value("${spring.datasource.max-pool-prepared-statement-per-connection-size}")
  27. private int maxPoolPreparedStatementPerConnectionSize;
  28. @Value("${spring.datasource.validation-query}")
  29. private String validationQuery;
  30. @Value("${spring.datasource.test-while-idle}")
  31. private boolean testWhileIdle;
  32. @Value("${spring.datasource.test-on-borrow}")
  33. private boolean testOnBorrow;
  34. @Value("${spring.datasource.test-on-return}")
  35. private boolean testOnReturn;
  36. @Value("{spring.datasource.connection-properties}")
  37. private String connectionProperties;
  38. @Bean
  39. @Primary
  40. @ConfigurationProperties("spring.datasource.druid")
  41. public DataSource dataSource() {
  42. DruidDataSource datasource = new DruidDataSource();
  43. datasource.setUrl(url);
  44. datasource.setUsername(username);
  45. datasource.setPassword(password);
  46. datasource.setDriverClassName(driverClassName);
  47. datasource.setInitialSize(initialSize);
  48. datasource.setMinIdle(minIdle);
  49. datasource.setMaxActive(maxActive);
  50. datasource.setMaxWait(maxWait);
  51. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  52. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  53. datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
  54. datasource.setValidationQuery(validationQuery);
  55. datasource.setTestWhileIdle(testWhileIdle);
  56. datasource.setTestOnBorrow(testOnBorrow);
  57. datasource.setTestOnReturn(testOnReturn);
  58. datasource.setPoolPreparedStatements(poolPreparedStatements);
  59. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  60. datasource.setConnectionProperties(connectionProperties);
  61. log.info("===========数据库连接" + url + "===========");
  62. return datasource;
  63. }
  64. @Bean(name = "dataSource")
  65. @Primary
  66. @ConfigurationProperties("spring.datasource.druid")
  67. public DataSource dataSource(){
  68. log.info("===========数据库连接" + url + "===========");
  69. return DruidDataSourceBuilder.create().build();
  70. }
  71. @Value("${mybatis.config-location}")
  72. private String configLocation;
  73. @Value("${mybatis.mapper-locations}")
  74. private String mapperLocations;
  75. @Value("${mybatis.type-aliases-package}")
  76. private String typeAliasesPackage;
  77. @Bean(name = "sqlSessionFactory")
  78. @Primary
  79. SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource")DataSource dataSource) throws Exception {
  80. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  81. bean.setDataSource(dataSource);
  82. bean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
  83. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
  84. bean.setTypeAliasesPackage(typeAliasesPackage);
  85. return bean.getObject();
  86. }
  87. @Bean
  88. @Primary
  89. public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
  90. return new SqlSessionTemplate(sqlSessionFactory);
  91. }
  92. /**
  93. * 监控页面相关
  94. */
  95. @Value("spring.datasource.druid.stat-view-servlet.url-pattern")
  96. private String urlPattern;
  97. @Value("spring.datasource.druid.stat-view-servlet.reset-enable")
  98. private String resetEnable;
  99. @Value("spring.datasource.druid.stat-view-servlet.login-username")
  100. private String loginUsername;
  101. @Value("spring.datasource.druid.stat-view-servlet.login-password")
  102. private String loginPassword;
  103. /**
  104. * 配置 Druid 监控界面
  105. * 内置没有web.xml文件,使用 SpringBoot 注册 Servlet 方式配置
  106. */
  107. @Bean
  108. public ServletRegistrationBean statViewServlet() {
  109. ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
  110. // 这些参数可以在StatViewServlet 的父类 ResourceServlet 中找到
  111. Map<String, String> initParams = new HashMap<>();
  112. initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
  113. initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
  114. // 页面允许某用户可以访问
  115. // initParams.put("allow", "localhost"):表示只有本机可以访问
  116. // 第二参数为空或者为null时,表示允许所有访问
  117. initParams.put("allow", "");
  118. // 页面拒绝xxx访问
  119. // initParams.put("xxx", "127.0.0.1"):表示禁止此ip访问
  120. // 设置初始化参数
  121. bean.setInitParameters(initParams);
  122. return bean;
  123. }

Logback

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" scanPeriod="10 seconds">
  3. <contextName>logback</contextName>
  4. <!-- 给某些包设置特定的日志级别 -->
  5. <logger name="org.springframework" level="WARN"/>
  6. <logger name="druid.sql" level="WARN"/>
  7. <logger name="springfox.documentation" level="WARN"/>
  8. <logger name="org.hibernate" level="WARN"/>
  9. <logger name="org.mybatis" level="WARN"/>
  10. <logger name="com.alibaba" level="WARN"/>
  11. <!-- 设置es的日志级别 `-->
  12. <logger name="org.springframework.data.elasticsearch.client.WIRE" level="trace"/>
  13. <logger name="org.springframework.data.convert.CustomConversions" level="ERROR"/>
  14. <springProperty scope="context" name="logLevel" source="logging.level"/>
  15. <!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
  16. <property name="LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
  17. <!-- <property name="LOG_PATTERN" value="%msg%n" />-->
  18. <!-- <property name="LOG_PATTERN" value="{'date':'%date{yyyy-MM-dd HH:mm:ss.SSS}', 'process':'%thread', 'level':'%-5level', 'author':'%logger{36}','msg':%msg}%n" />-->
  19. <!-- 定义日志存储的路径 -->
  20. <property name="FILE_PATH" value="./logs" />
  21. <!-- 控制台输出日志 -->
  22. <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
  23. <encoder>
  24. <!-- 按照上面配置的LOG_PATTERN来打印日志 -->
  25. <pattern>${LOG_PATTERN}</pattern>
  26. </encoder>
  27. </appender>
  28. <!-- 每天生成一个日志文件,每月生成一个文件夹,每天超出100M新增一个文件。 -->
  29. <appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
  30. <file>${FILE_PATH}/log_current.log</file>
  31. <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
  32. <!--日志文件输出的文件名-->
  33. <FileNamePattern>${FILE_PATH}/%d{yyyy-MM, aux}/log-%d{yyyy-MM-dd}.%i.log</FileNamePattern>
  34. <!-- 日志文件最大尺寸 -->
  35. <maxFileSize>100MB</maxFileSize>
  36. </rollingPolicy>
  37. <encoder>
  38. <pattern>${LOG_PATTERN}</pattern>
  39. </encoder>
  40. </appender>
  41. <!-- 日志输出级别 -->
  42. <root level="${logLevel}">
  43. <appender-ref ref="console" />
  44. <appender-ref ref="rollingFile" />
  45. </root>
  46. </configuration>
  1. # 设置日志级别
  2. logging:
  3. level:
  4. com.csj.demo.business: debug

JWT

  1. 标准中注册的声明 (建议但不强制使用)
  2. iss: jwt签发者
  3. sub: jwt所面向的用户
  4. aud: 接收jwt的一方
  5. exp: jwt的过期时间,这个过期时间必须要大于签发时间
  6. nbf: 定义在什么时间之前,该jwt都是不可用的.
  7. iat: jwt的签发时间
  8. jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。
  1. 自定义注解跳过验证
  2. @PassToken:跳过验证,通常是入口方法上用这个,比如登录接口

jwt工具类

  1. package com.csj.demo.business.utils;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.JWTCreator;
  4. import com.auth0.jwt.JWTVerifier;
  5. import com.auth0.jwt.algorithms.Algorithm;
  6. import com.auth0.jwt.exceptions.JWTDecodeException;
  7. import com.auth0.jwt.interfaces.Claim;
  8. import com.csj.demo.business.exception.OperationException;
  9. import com.csj.demo.business.exception.ResultUtils;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. * @Desc : jwt工具类
  16. * @Author : chen
  17. * @Date : 2022/4/25 13:59
  18. */
  19. public class JwtUtils {
  20. //盐值
  21. private static String SECRET = "superadmin";
  22. //jwt的过期时间
  23. private static Integer EXP = 30;
  24. //jwt签发者
  25. private static String ISS = "business";
  26. //接收人员
  27. private static String AUD = "WEB";
  28. //面向用户
  29. private static String SUB = "WEB";
  30. /**
  31. * 获取token
  32. * @param userId
  33. * @param userName
  34. * @return
  35. */
  36. public static String getJWTToken(String userId, String userName){
  37. return createToken(userId,userName);
  38. }
  39. /**
  40. * 签发token
  41. * @param userId
  42. * @param userName
  43. * @return
  44. */
  45. private static String createToken(String userId, String userName) {
  46. //签发时间
  47. Date iatDate = new Date();
  48. //过期时间
  49. Calendar nowTime = Calendar.getInstance();
  50. nowTime.add(Calendar.MINUTE, EXP);
  51. Date expiresDate = nowTime.getTime();
  52. // header Map
  53. Map<String, Object> header = new HashMap<>();
  54. //加密算法
  55. header.put("alg", "HS256");
  56. //类型 jwt
  57. header.put("typ", "JWT");
  58. JWTCreator.Builder builder = JWT.create();
  59. //header
  60. builder.withHeader(header);
  61. //发行人,发行时间,过期时间
  62. builder.withIssuer(ISS)
  63. .withIssuedAt(iatDate)
  64. .withExpiresAt(expiresDate);
  65. //载荷,负载信息 可在验证过后从token中获取到
  66. builder.withClaim("userName", userName);
  67. //aud 接收人员,sub 面向的用户
  68. builder.withAudience(userId)
  69. .withSubject(SUB);
  70. //token 唯一标识
  71. builder.withJWTId(userId);
  72. //加密
  73. return builder.sign(Algorithm.HMAC256(userId + SECRET));
  74. }
  75. /**
  76. * 验证token
  77. * @param token
  78. * @param userId
  79. * @throws OperationException
  80. */
  81. public static void verifyToken(String token, String userId) throws OperationException {
  82. try {
  83. JWTVerifier verifier = JWT.require(Algorithm.HMAC256(userId + SECRET)).build();
  84. verifier.verify(token);
  85. } catch (Exception e) {
  86. //效验失败 抛出异常
  87. throw new OperationException(ResultUtils.JWT_ERRCODE_NULL);
  88. }
  89. }
  90. /**
  91. * 获取接收人员
  92. * @param token
  93. * @return
  94. * @throws OperationException
  95. */
  96. public static String getAudience(String token) throws OperationException {
  97. String audience = null;
  98. try {
  99. audience = JWT.decode(token).getAudience().get(0);
  100. } catch (JWTDecodeException j) {
  101. //这里是token解析失败
  102. throw new OperationException(ResultUtils.JWT_ERRCODE_NULL);
  103. }
  104. return audience;
  105. }
  106. /**
  107. * 获取token载荷
  108. * @param token
  109. * @param name
  110. * @return
  111. */
  112. public static Claim getClaimByName(String token, String name) {
  113. return JWT.decode(token).getClaim(name);
  114. }
  115. }
  1. package com.csj.demo.business.annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * @Desc : 自定义注解:跳过token
  8. * @Author : chen
  9. * @Date : 2022/4/25 16:38
  10. */
  11. @Target({ElementType.METHOD, ElementType.TYPE})
  12. @Retention(RetentionPolicy.RUNTIME)
  13. public @interface PassToken {
  14. boolean required() default true;
  15. }

自定义拦截器验证token

  1. package com.csj.demo.business.interceptor;
  2. import com.csj.demo.business.annotation.PassToken;
  3. import com.csj.demo.business.exception.OperationException;
  4. import com.csj.demo.business.exception.ResultUtils;
  5. import com.csj.demo.business.service.UserService;
  6. import com.csj.demo.business.utils.JwtUtils;
  7. import com.oracle.tools.packager.Log;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.method.HandlerMethod;
  10. import org.springframework.web.servlet.HandlerInterceptor;
  11. import org.springframework.web.servlet.ModelAndView;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.lang.reflect.Method;
  15. /**
  16. * @Desc : jwt验证拦截器
  17. * @Author : chen
  18. * @Date : 2022/4/25 16:24
  19. */
  20. public class JwtAuthenticationInterceptor implements HandlerInterceptor {
  21. @Autowired
  22. private UserService userService;
  23. @Override
  24. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
  25. // 从请求头中取出 token 这里需要和前端约定好把jwt放到请求头一个叫token的地方
  26. String token = httpServletRequest.getHeader("token");
  27. // 如果不是映射到方法直接通过
  28. if (!(object instanceof HandlerMethod)) {
  29. return true;
  30. }
  31. HandlerMethod handlerMethod = (HandlerMethod) object;
  32. Method method = handlerMethod.getMethod();
  33. //检查是否有passtoken注释,有则跳过认证
  34. if (method.isAnnotationPresent(PassToken.class)) {
  35. PassToken passToken = method.getAnnotation(PassToken.class);
  36. if (passToken.required()) {
  37. return true;
  38. }
  39. }else {
  40. //默认全部检查
  41. Log.info("jwt拦截验证Token");
  42. // 执行认证
  43. if (token == null) {
  44. //这里其实是登录失效,没token了
  45. throw new OperationException(ResultUtils.JWT_ERRCODE_NULL);
  46. }
  47. // 获取 token 中的 user Name
  48. String userId = JwtUtils.getAudience(token);
  49. //验证用户是否存在
  50. boolean b = userService.existsUserById(Long.parseLong(userId));
  51. if (!b) {
  52. throw new OperationException(ResultUtils.INVALID_USER);
  53. }
  54. // 验证 token
  55. JwtUtils.verifyToken(token, userId);
  56. //获取载荷内容
  57. String userName = JwtUtils.getClaimByName(token, "userName").asString();
  58. return true;
  59. }
  60. return true;
  61. }
  62. @Override
  63. public void postHandle(HttpServletRequest httpServletRequest,
  64. HttpServletResponse httpServletResponse,
  65. Object o, ModelAndView modelAndView) throws Exception {
  66. }
  67. @Override
  68. public void afterCompletion(HttpServletRequest httpServletRequest,
  69. HttpServletResponse httpServletResponse,
  70. Object o, Exception e) throws Exception {
  71. }
  72. }

配置自定义拦截器

  1. package com.csj.demo.business.config;
  2. import com.csj.demo.business.interceptor.JwtAuthenticationInterceptor;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7. /**
  8. * @Desc : 拦截器
  9. * @Author : chen
  10. * @Date : 2022/4/25 16:21
  11. */
  12. @Configuration
  13. public class InterceptorConfig implements WebMvcConfigurer {
  14. @Override
  15. public void addInterceptors(InterceptorRegistry registry) {
  16. //默认拦截所有路径
  17. registry.addInterceptor(authenticationInterceptor())
  18. .addPathPatterns("/**");
  19. }
  20. @Bean
  21. public JwtAuthenticationInterceptor authenticationInterceptor() {
  22. return new JwtAuthenticationInterceptor();
  23. }
  24. }

热部署devtools

  1. <!--devtools-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-devtools</artifactId>
  5. <scope>runtime</scope>
  6. <optional>true</optional>
  7. </dependency>
  1. spring:
  2. devtools:
  3. add-properties: false
  4. restart:
  5. enabled: true
  6. additional-paths: src/main/java
  7. additional-exclude: static/**,public/**
  8. #exclude: static/**