• Redis实战——短信登录


    目录

    1 基于Seesion实现短信登录

    1.1 发送短信验证码 

     1.2 登录功能

    2 使用Redis进行短信验证码校验登录

    2.1 Seesion方法存在的问题

    2.2 发送短信验证码

    2.3  验证码校验及登录功能

     3.拦截器优化


    1 基于Seesion实现短信登录

    1.1 发送短信验证码 

    发送验证码请求路径 /user/code

    Controller层

    1. /**
    2. * 发送手机验证码
    3. */
    4. @PostMapping("code")
    5. public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
    6. // TODO 发送短信验证码并保存验证码
    7. return userService.sendCode(phone,session);
    8. }

    Service层及Service实现

    1. public interface IUserService extends IService {
    2. Result sendCode(String phone, HttpSession session);
    3. }
    1. package com.hmdp.service.impl;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.util.RandomUtil;
    4. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    6. import com.hmdp.dto.LoginFormDTO;
    7. import com.hmdp.dto.Result;
    8. import com.hmdp.dto.UserDTO;
    9. import com.hmdp.entity.User;
    10. import com.hmdp.mapper.UserMapper;
    11. import com.hmdp.service.IUserService;
    12. import com.hmdp.utils.RegexPatterns;
    13. import com.hmdp.utils.RegexUtils;
    14. import lombok.extern.slf4j.Slf4j;
    15. import org.apache.catalina.manager.util.SessionUtils;
    16. import org.springframework.beans.BeanUtils;
    17. import org.springframework.beans.factory.annotation.Autowired;
    18. import org.springframework.stereotype.Service;
    19. import javax.servlet.http.HttpSession;
    20. import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
    21. /**
    22. *

    23. * 服务实现类
    24. *

    25. *
    26. * @author 虎哥
    27. * @since 2021-12-22
    28. */
    29. @Slf4j
    30. @Service
    31. public class UserServiceImpl extends ServiceImpl implements IUserService {
    32. @Override
    33. public Result sendCode(String phone, HttpSession session) {
    34. //1.校验手机号
    35. if (RegexUtils.isPhoneInvalid(phone)){
    36. //2.如果错误,返回错误信息
    37. return Result.fail("手机号码格式错误!");
    38. }
    39. //3.生成验证码
    40. String code = RandomUtil.randomNumbers(6);
    41. //4.保存验证码到session中去
    42. session.setAttribute("code",code);
    43. //5.发送验证码
    44. log.debug("手机验证码为:{}",code);
    45. return Result.ok();
    46. }
    47. }

     1.2 登录功能

    请求路径:user/login

     

    Controller层

    1. /**
    2. * 登录功能
    3. * @param loginForm 登录参数,包含手机号、验证码;或者手机号、密码
    4. */
    5. @PostMapping("/login")
    6. public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
    7. // TODO 实现登录功能
    8. return userService.login(loginForm,session);
    9. }

     Service层及Service实现

    1. public interface IUserService extends IService {
    2. Result login(LoginFormDTO loginForm, HttpSession session);
    3. }
    1. package com.hmdp.service.impl;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.util.RandomUtil;
    4. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    6. import com.hmdp.dto.LoginFormDTO;
    7. import com.hmdp.dto.Result;
    8. import com.hmdp.dto.UserDTO;
    9. import com.hmdp.entity.User;
    10. import com.hmdp.mapper.UserMapper;
    11. import com.hmdp.service.IUserService;
    12. import com.hmdp.utils.RegexPatterns;
    13. import com.hmdp.utils.RegexUtils;
    14. import lombok.extern.slf4j.Slf4j;
    15. import org.apache.catalina.manager.util.SessionUtils;
    16. import org.springframework.beans.BeanUtils;
    17. import org.springframework.beans.factory.annotation.Autowired;
    18. import org.springframework.stereotype.Service;
    19. import javax.servlet.http.HttpSession;
    20. import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
    21. /**
    22. *

    23. * 服务实现类
    24. *

    25. *
    26. * @author 虎哥
    27. * @since 2021-12-22
    28. */
    29. @Slf4j
    30. @Service
    31. public class UserServiceImpl extends ServiceImpl implements IUserService {
    32. @Override
    33. public Result login(LoginFormDTO loginForm, HttpSession session) {
    34. String phone = loginForm.getPhone();
    35. //1.校验手机号
    36. if (RegexUtils.isPhoneInvalid(phone)){
    37. //2.如果错误,返回错误信息
    38. return Result.fail("手机号码格式错误!");
    39. }
    40. //2.校验验证码
    41. String code = loginForm.getCode();
    42. String sendCode = (String) session.getAttribute("code");
    43. if (code != null || !code.equals(sendCode)){
    44. //验证码不一致
    45. Result.fail("验证码错误!");
    46. }
    47. //验证码相同,查询手机号
    48. User user = query().eq("phone", loginForm.getPhone()).one();
    49. if (user == null) {
    50. //用户不存在,创建一个新用户并且保存到数据库中
    51. user = createNewUser(phone);
    52. }
    53. //用户存在,存入Session
    54. session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
    55. return Result.ok();
    56. }
    57. private User createNewUser(String phone) {
    58. //1.创建用户
    59. User user = new User();
    60. user.setPhone(phone);
    61. user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
    62. //2.保存用户
    63. save(user);
    64. return user;
    65. }
    66. }

    1.3 登录校验功能(配置拦截器

     

        

    编写拦截器类:

    1. package com.hmdp.utils;
    2. import com.hmdp.dto.UserDTO;
    3. import org.springframework.web.servlet.HandlerInterceptor;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. import javax.servlet.http.HttpSession;
    7. /**
    8. * @Author 华子
    9. * @Date 2022/11/20 17:30
    10. * @Version 1.0
    11. */
    12. public class LoginInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. //1.获session
    16. HttpSession session = request.getSession();
    17. //2.获取用户信息
    18. Object user = session.getAttribute("user");
    19. //3.判断用户信息是否存在
    20. if (user == null){
    21. //4.不存在,拦截
    22. response.setStatus(401);
    23. return false;
    24. }
    25. //5.存在,保存用户信息到ThreadLocal
    26. UserHolder.saveUser((UserDTO) user);
    27. //6.放行
    28. return true;
    29. }
    30. @Override
    31. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    32. //移除用户
    33. UserHolder.removeUser();
    34. }
    35. }

    配置添加拦截器到SpringMvc中(配置拦截路径)

    1. package com.hmdp.config;
    2. import com.hmdp.utils.LoginInterceptor;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    6. /**
    7. * @Author 华子
    8. * @Date 2022/11/20 17:38
    9. * @Version 1.0
    10. */
    11. @Configuration
    12. public class MvcConfig implements WebMvcConfigurer {
    13. @Override
    14. public void addInterceptors(InterceptorRegistry registry) {
    15. registry.addInterceptor(new LoginInterceptor())
    16. .excludePathPatterns(
    17. "/shop/**",
    18. "/voucher/**",
    19. "/shop-type/**",
    20. "/upload/**",
    21. "/blog/hot",
    22. "/user/code",
    23. "/user/login"
    24. );
    25. }
    26. }

    最后Controller层返回用户信息

    1. @GetMapping("/me")
    2. public Result me(){
    3. // TODO 获取当前登录的用户并返回
    4. UserDTO user = UserHolder.getUser();
    5. return Result.ok(user);
    6. }

    2 使用Redis进行短信验证码校验登录

    2.1 Seesion方法存在的问题

    session共享问题

    多台Tomcat并不共享session存储空间,当请求切换到不同tomcat服务时导致数据丢失的问题。 

    session的替代方案应该满足:

    数据共享

    内存存储

    key、value结构

    无可厚非,就说我们的Reids啦~

    2.2 发送短信验证码

    这步操作和之前的Session很相同,只是我们这次把验证码保存到Redis当中

     

    对于验证码的保存,我们选择String类型操作,key用手机号(唯一性)value就是验证码

     

    代码:(其余操作一样,就是验证码本来是存到Session中,改为存到Reids) 

     

    1. package com.hmdp.service.impl;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.bean.copier.CopyOptions;
    4. import cn.hutool.core.lang.UUID;
    5. import cn.hutool.core.util.RandomUtil;
    6. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    7. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    8. import com.hmdp.dto.LoginFormDTO;
    9. import com.hmdp.dto.Result;
    10. import com.hmdp.dto.UserDTO;
    11. import com.hmdp.entity.User;
    12. import com.hmdp.mapper.UserMapper;
    13. import com.hmdp.service.IUserService;
    14. import com.hmdp.utils.RegexPatterns;
    15. import com.hmdp.utils.RegexUtils;
    16. import lombok.extern.slf4j.Slf4j;
    17. import org.apache.catalina.manager.util.SessionUtils;
    18. import org.springframework.beans.BeanUtils;
    19. import org.springframework.beans.factory.annotation.Autowired;
    20. import org.springframework.data.redis.core.StringRedisTemplate;
    21. import org.springframework.stereotype.Service;
    22. import javax.annotation.Resource;
    23. import javax.servlet.http.HttpSession;
    24. import java.util.HashMap;
    25. import java.util.Map;
    26. import java.util.concurrent.TimeUnit;
    27. import static com.hmdp.utils.RedisConstants.*;
    28. import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
    29. /**
    30. *

    31. * 服务实现类
    32. *

    33. *
    34. * @author 虎哥
    35. * @since 2021-12-22
    36. */
    37. @Slf4j
    38. @Service
    39. public class UserServiceImpl extends ServiceImpl implements IUserService {
    40. @Resource
    41. private StringRedisTemplate stringRedisTemplate;
    42. @Override
    43. public Result sendCode(String phone, HttpSession session) {
    44. //1.校验手机号
    45. if (RegexUtils.isPhoneInvalid(phone)){
    46. //2.如果错误,返回错误信息
    47. return Result.fail("手机号码格式错误!");
    48. }
    49. //3.生成验证码
    50. String code = RandomUtil.randomNumbers(6);
    51. //4.保存验证码到session中去
    52. // session.setAttribute("code",code);
    53. //4.保存验证码到redis中去
    54. stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
    55. //5.发送验证码
    56. log.debug("手机验证码为:{}",code);
    57. return Result.ok();
    58. }
    59. }

    2.3  验证码校验及登录功能

    这一步明显要比上一步复杂的多了,我们一步一步来

    首先,就是用户每次访问的时候,每次的路径都是不一样的,而Seesion是从Cookie中获取唯一的SessionId来确保唯一性,以此取得用户值,而对于Redis,我们及需要一个唯一的标识符,就是我们的Token(使用UUID生成的随机字符串)

    和之前的Session操作不同的地方在于

    1. 使用手机号为key去Redis中获取验证码

    2. 使用随机生成的字符串Token保存用户数据

    3.返回Token数据给前端,由前端保存到请求头的“Authorization”中 

    温馨小提示:这里我们使用Map操作来保存用户数据~

    具体实现代码如下:

    1. package com.hmdp.service.impl;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.bean.copier.CopyOptions;
    4. import cn.hutool.core.lang.UUID;
    5. import cn.hutool.core.util.RandomUtil;
    6. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    7. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    8. import com.hmdp.dto.LoginFormDTO;
    9. import com.hmdp.dto.Result;
    10. import com.hmdp.dto.UserDTO;
    11. import com.hmdp.entity.User;
    12. import com.hmdp.mapper.UserMapper;
    13. import com.hmdp.service.IUserService;
    14. import com.hmdp.utils.RegexPatterns;
    15. import com.hmdp.utils.RegexUtils;
    16. import lombok.extern.slf4j.Slf4j;
    17. import org.apache.catalina.manager.util.SessionUtils;
    18. import org.springframework.beans.BeanUtils;
    19. import org.springframework.beans.factory.annotation.Autowired;
    20. import org.springframework.data.redis.core.StringRedisTemplate;
    21. import org.springframework.stereotype.Service;
    22. import javax.annotation.Resource;
    23. import javax.servlet.http.HttpSession;
    24. import java.util.HashMap;
    25. import java.util.Map;
    26. import java.util.concurrent.TimeUnit;
    27. import static com.hmdp.utils.RedisConstants.*;
    28. import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
    29. /**
    30. *

    31. * 服务实现类
    32. *

    33. *
    34. * @author 虎哥
    35. * @since 2021-12-22
    36. */
    37. @Slf4j
    38. @Service
    39. public class UserServiceImpl extends ServiceImpl implements IUserService {
    40. @Resource
    41. private StringRedisTemplate stringRedisTemplate;
    42. @Override
    43. public Result login(LoginFormDTO loginForm, HttpSession session) {
    44. String phone = loginForm.getPhone();
    45. //1.校验手机号
    46. if (RegexUtils.isPhoneInvalid(phone)){
    47. //2.如果错误,返回错误信息
    48. return Result.fail("手机号码格式错误!");
    49. }
    50. //2.校验验证码
    51. //2.1 从redis中获取验证码
    52. String sendCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
    53. String code = loginForm.getCode();
    54. // String sendCode = (String) session.getAttribute("code");
    55. if (code != null || !code.equals(sendCode)){
    56. //验证码不一致
    57. Result.fail("验证码错误!");
    58. }
    59. //验证码相同,查询手机号
    60. User user = query().eq("phone", loginForm.getPhone()).one();
    61. if (user == null) {
    62. //用户不存在,创建一个新用户并且保存到数据库中
    63. user = createNewUser(phone);
    64. }
    65. // 用户存在,将用户数据存入Redis
    66. //随机生成一个token
    67. String token = UUID.randomUUID().toString(true);
    68. //获取用户数据并转成Map集合
    69. UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
    70. Map userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
    71. CopyOptions.create()
    72. .setIgnoreNullValue(true)
    73. .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString())
    74. );
    75. //将用户数据存入redis当中
    76. String tokenKey = LOGIN_USER_KEY+token;
    77. stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
    78. //设置有效期,防止用户过多,导致内存不足
    79. stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);
    80. // session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
    81. return Result.ok(token);
    82. }
    83. private User createNewUser(String phone) {
    84. //1.创建用户
    85. User user = new User();
    86. user.setPhone(phone);
    87. user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
    88. //2.保存用户
    89. save(user);
    90. return user;
    91. }
    92. }

    还没完,Session操作中,我们用户每次请求,都会重新设置存活时间,以确保用户可以持续,而我们使用Redis时,可以在拦截器中设置每次拦截到,重新设置Redis字段的存活时间 。

    和Session使用的拦截器不同点在于

    1.我们要先获取请求头中的token,用来获取用户数据

    2.保存完用户数据后,我们需要重新设置Redis中key的存活时间

    具体代码如下:

    1. package com.hmdp.utils;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.util.StrUtil;
    4. import com.hmdp.dto.UserDTO;
    5. import org.springframework.data.redis.core.StringRedisTemplate;
    6. import org.springframework.web.servlet.HandlerInterceptor;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.util.Map;
    10. import java.util.concurrent.TimeUnit;
    11. /**
    12. * @Author 华子
    13. * @Date 2022/11/20 17:30
    14. * @Version 1.0
    15. */
    16. public class RefreshTokenInterceptor implements HandlerInterceptor {
    17. private StringRedisTemplate stringRedisTemplate;
    18. public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
    19. this.stringRedisTemplate = stringRedisTemplate;
    20. }
    21. @Override
    22. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    23. //1.获取请求头中的token
    24. String token = request.getHeader("authorization");
    25. if (StrUtil.isBlank(token)) {
    26. return true;
    27. }
    28. //2.获取用户信息
    29. String key = RedisConstants.LOGIN_USER_KEY + token;
    30. Map userMap = stringRedisTemplate.opsForHash().entries(key);
    31. //3.判断用户信息是否存在
    32. if (userMap.isEmpty()){
    33. return true;
    34. }
    35. //5.存在,保存用户信息到ThreadLocal
    36. //将从redis中获取到的userMap转成UserDto
    37. UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
    38. UserHolder.saveUser(userDTO);
    39. //6.刷新存活时间
    40. stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
    41. //7.放行
    42. return true;
    43. }
    44. @Override
    45. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    46. //移除用户
    47. UserHolder.removeUser();
    48. }
    49. }

    Mvc配置类(MvcConfig):

    1. package com.hmdp.config;
    2. import com.hmdp.utils.LoginInterceptor;
    3. import com.hmdp.utils.RefreshTokenInterceptor;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.data.redis.core.StringRedisTemplate;
    6. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    8. import javax.annotation.Resource;
    9. /**
    10. * @Author 华子
    11. * @Date 2022/11/20 17:38
    12. * @Version 1.0
    13. */
    14. @Configuration
    15. public class MvcConfig implements WebMvcConfigurer {
    16. @Resource
    17. private StringRedisTemplate stringRedisTemplate;
    18. @Override
    19. public void addInterceptors(InterceptorRegistry registry) {
    20. registry.addInterceptor(new LoginInterceptor())
    21. .excludePathPatterns(
    22. "/shop/**",
    23. "/voucher/**",
    24. "/shop-type/**",
    25. "/upload/**",
    26. "/blog/hot",
    27. "/user/code",
    28. "/user/login"
    29. );
    30. }
    31. }

    这里有个小知识点,我们自己创造的类,Spring无法帮我们自动注入,所以我们在Mvc配置类中进行注入 

     

    这样就可以成功的注入StringRedisTemplate了~ 

     3.拦截器优化

    因为我们上述的拦截器只拦截了部分请求,还没做到百分百刷新用户的存活时间,所以我们可以这样做:

    在最外层在加上一个拦截器,拦截所有用户,用于专门刷新存活时间且放行,而第二个拦截器用于判断ThreadLocal中是否含有用户信息,没有就拦截。

     

    具体实现代码:

    最外层拦截器:(只做刷新)

    1. package com.hmdp.utils;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.util.StrUtil;
    4. import com.hmdp.dto.UserDTO;
    5. import org.springframework.data.redis.core.StringRedisTemplate;
    6. import org.springframework.web.servlet.HandlerInterceptor;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.util.Map;
    10. import java.util.concurrent.TimeUnit;
    11. /**
    12. * @Author 华子
    13. * @Date 2022/11/20 17:30
    14. * @Version 1.0
    15. */
    16. public class RefreshTokenInterceptor implements HandlerInterceptor {
    17. private StringRedisTemplate stringRedisTemplate;
    18. public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
    19. this.stringRedisTemplate = stringRedisTemplate;
    20. }
    21. @Override
    22. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    23. //1.获取请求头中的token
    24. String token = request.getHeader("authorization");
    25. if (StrUtil.isBlank(token)) {
    26. return true;
    27. }
    28. //2.获取用户信息
    29. String key = RedisConstants.LOGIN_USER_KEY + token;
    30. Map userMap = stringRedisTemplate.opsForHash().entries(key);
    31. //3.判断用户信息是否存在
    32. if (userMap.isEmpty()){
    33. return true;
    34. }
    35. //5.存在,保存用户信息到ThreadLocal
    36. //将从redis中获取到的userMap转成UserDto
    37. UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
    38. UserHolder.saveUser(userDTO);
    39. //6.刷新存活时间
    40. stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
    41. //7.放行
    42. return true;
    43. }
    44. @Override
    45. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    46. //移除用户
    47. UserHolder.removeUser();
    48. }
    49. }

    第二次拦截器:(只做拦截)

    1. package com.hmdp.utils;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import cn.hutool.core.util.StrUtil;
    4. import com.hmdp.dto.UserDTO;
    5. import io.netty.util.internal.StringUtil;
    6. import org.springframework.beans.BeanUtils;
    7. import org.springframework.data.redis.core.StringRedisTemplate;
    8. import org.springframework.util.StringUtils;
    9. import org.springframework.web.servlet.HandlerInterceptor;
    10. import javax.servlet.http.HttpServletRequest;
    11. import javax.servlet.http.HttpServletResponse;
    12. import javax.servlet.http.HttpSession;
    13. import java.util.Map;
    14. import java.util.concurrent.TimeUnit;
    15. /**
    16. * @Author 华子
    17. * @Date 2022/11/20 17:30
    18. * @Version 1.0
    19. */
    20. public class LoginInterceptor implements HandlerInterceptor {
    21. @Override
    22. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    23. //1.判断ThreadLocal中是否存在用户信息
    24. if (UserHolder.getUser() == null){
    25. //没有,拦截
    26. response.setStatus(401);
    27. return false;
    28. }
    29. //2. 有,放行
    30. return true;
    31. }
    32. }

    Mvc配置类:

    这里面主要设置了添加拦截器,设置第二个拦截器需要拦截的路径 和两个拦截器的优先级。

    1. package com.hmdp.config;
    2. import com.hmdp.utils.LoginInterceptor;
    3. import com.hmdp.utils.RefreshTokenInterceptor;
    4. import org.springframework.context.annotation.Configuration;
    5. import org.springframework.data.redis.core.StringRedisTemplate;
    6. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    8. import javax.annotation.Resource;
    9. /**
    10. * @Author 华子
    11. * @Date 2022/11/20 17:38
    12. * @Version 1.0
    13. */
    14. @Configuration
    15. public class MvcConfig implements WebMvcConfigurer {
    16. @Resource
    17. private StringRedisTemplate stringRedisTemplate;
    18. @Override
    19. public void addInterceptors(InterceptorRegistry registry) {
    20. registry.addInterceptor(new LoginInterceptor())
    21. .excludePathPatterns(
    22. "/shop/**",
    23. "/voucher/**",
    24. "/shop-type/**",
    25. "/upload/**",
    26. "/blog/hot",
    27. "/user/code",
    28. "/user/login"
    29. ).order(1);
    30. registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).order(0);
    31. }
    32. }

     

     

     

  • 相关阅读:
    hive笔记
    【owt-server】Internal Transport 5 : InternalServer 流管理、流通知、session管理
    C++学习笔记02-面向对象及类的引入
    蓝桥杯每日一题20223.9.26
    优雅的实现EasyPoi动态导出列的两种方式
    【数据集标注制作】视频剪切标注1——类DarkLabel软件
    Postman API测试工具的使用
    Multi-Adapter RGBT Tracking代码学习(一)
    MySQL数据库管理
    python的环境安装(版本3.10.6)
  • 原文地址:https://blog.csdn.net/qq_59212867/article/details/127951978