【无标题】springboot+redis+thymeleaf实现互斥登录!!

1.实现思路

        添加拦截器,设置UUID让token作为唯一标识,存入redis中当value,当前登陆者的账户为key,当前登陆者的token与我们redis中的token值相同则通过,否则返回false,表示设备已在其他地方登录。

2.连接linux启动redis

3.代码实现 

        3.1使用Spring Initializr 创建Springboot项目

        3.2 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 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>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.liwei</groupId>
    <artifactId>springboot-dandian</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-dandian</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </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.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <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>

        3.3yml配置文件

spring:
  redis:
    database: 0    #redis��Ĭ�����ݿ�Ϊ0
    host: 192.168.27.130  #����redis��ip
    port: 6379  #����redis�Ķ˿ں�
    password:   #����redis������ Ĭ��Ϊ��
    jedis:
      pool:
        max-total: 200    #����redis������Ŀ
        max-active: 100  #����redis�����
        max-idle: 8      #������������
        min-idle: 5     #������������
  datasource:
    url: jdbc:mysql://localhost:3306/basketball?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
 
server:
  port: 8888

4.后端代码实现

         4.1TokenUtil实体类

package com.liwei.pojo;

import lombok.Data;

@Data
public class TokenUtil {

    //用户存储登录者账户
    private String username;

    //唯一token码
    private String token;
}

        4.2实现HandlerInterceptor

package com.liwei.config;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public LoginInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getParameter("token");
        String username = request.getParameter("username");
        if(token == null){
            response.setStatus(401);
            return false;
        }

        //给username进行缓存
        String tokenValue = redisTemplate.opsForValue().get(username);
        if(tokenValue!=null&&tokenValue.equals(token)){
            System.out.println("token正确,放行");
            return true;
        }
        response.setStatus(520);
        return false;
    }
}

        4.3实现WebMvcConfigurer配置config

package com.liwei.config;

import com.liwei.config.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor(redisTemplate))
                .excludePathPatterns("/index","/login");
    }
}

        4.4控制层userController

package com.liwei.controller;

import com.liwei.pojo.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
public class UserController {

    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;


    
    @PostMapping("/login")
    public String checkLogin(String username, String password, Model model){
        if (username.equals("liwei") && password.equals("123456")){
            String token = UUID.randomUUID().toString();
            TokenUtil tokenUtil = new TokenUtil();
            tokenUtil.setToken(token);
            tokenUtil.setUsername(username);
            model.addAttribute("tokenUtil",tokenUtil);
            redisTemplate.opsForValue().set(username,token);
        }
        return "add";
    }

    
    @GetMapping("/index")
    public String index(){
        return "index";
    }

    
    @PostMapping("/test")
    @ResponseBody
    public String test(){
        return "添加";
    }
}

   5.实现效果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值