用redis实现登录受限问题

如果10分钟内登录超过10次,返回登录受限,不能登陆(因为有可能是受到了攻击);

  • 用了redis的string数据类型
  • 每登陆一次自动+1
  • 参数的生命周期10分钟

目录如下:

前台jsp:(登陆成功跳一个hello页面,自己定义就好,登陆失败还是在当前页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>登录</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
</head>
<body>
    
    <p>用户名:<input name="userName" type="text" id="un" /></p>
    <p>密&nbsp;&nbsp;  码:<input name="password" type="password" id="pas"/></p>
    <p><input type="submit" value="添加" onclick="tian()"/></p>
    <p><input type="submit" value="登录" onclick="sub()"/></p>

<script type="text/javascript">
    function sub() {
        var uu = $("#un").val();
        var pa = $("#pas").val();
        $.ajax({
            url:"${pageContext.request.contextPath}/demo1/toHello/"+uu+"/"+pa,
            type:"get",
            dataType:"json",
            success:function (data) {
                if(data){
                    alert("登录成功!");
                    location.href="${pageContext.request.contextPath}/jsps/hello.jsp";
                }else {
                    alert("登陆失败!");
                    alert(${sessionScope.msg})
                    location.href="${pageContext.request.contextPath}/jsps/login.jsp";
                }

            },
            error:function () {
                alert("登陆失败!");
                alert(${sessionScope.msg})
                location.href="${pageContext.request.contextPath}/jsps/login.jsp";
            }
        });
    }
    
</script>
</body>
</html>

controller:(返回类型为boolean,10分钟内登陆次数大于10次,登陆受限)

@RequestMapping(value = "/demo1")
@Controller
public class UserCon {
    @Resource
    private UserService userService;
    @Resource
    private JedisPool jedisPool;
    @GetMapping("/toHello/{uu}/{pa}")
    @ResponseBody
    public Boolean toHello(@PathVariable("uu") String userName,@PathVariable("pa") String password,
                           HttpSession session){

        ManagerUser temp= userService.selectUser(userName,password);
        if (temp!=null) {
            //1、登陆时获取redis中的登陆次数,如果>10,打印登陆受限
            Long num=userService.getRedisLoginNum (temp.getId());
            System.out.println("10分钟内的登陆次数为: "+num);
            if(num>10) {
                session.setAttribute("msg","10分钟内登陆次数大于10次,因此,登陆受限!");

            }else {
                session.setAttribute("mu",temp);
                return true;
            }
        }
        return false;
    }
}

serviceImpl:

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private JedisClient jedisClient;
    private final String REDIS_LOGIN_PREFIX="redis_login_";
    
    @Override
    public ManagerUser selectUser(String userName, String password) {
        return userMapper.selectUser(userName,password);
    }

    @Override
    public Long getRedisLoginNum(Integer id) {
        //1.判断key值是否存在,如果不存在,设置一个值,如果存在,自增
        String key=REDIS_LOGIN_PREFIX+id;
        Long num=1L;
        if(jedisClient.exists(key)){
            num=jedisClient.incr(key);
        }else {
            jedisClient.setex(key, 600, "1");//单位是秒
        }
        return num;
    }
}

jedisClient:

package com.example.demo6.redis;

import java.util.List;

public interface JedisClient {

    String set(String key, String value);
    String get(String key);
    Boolean exists(String key);
    Long expire(String key, int seconds);
    Long ttl(String key);
    Long incr(String key);
    Long hset(String key, String field, String value);
    String hget(String key, String field);
    Long hdel(String key, String... field);
    Long lpush(String key, String value);
    List<String> lrange(String key, Integer startIndex, Integer endIndex);
    String ltrim(String key, Integer startIndex, Integer endIndex);
    Long rpush(String key, String value);
    String lindex(String key, Integer index);
    Long lrem(String key, Integer number, String value);
    Double zscore(String demandBrowseNumber, String toString);
    Double zincrby(String demandBrowseNumber, int i, String toString);
    String setex(String key,Integer number,String value);
}

JedisClientPool:(实现类)

package com.example.demo6.redis.impl;

import com.example.demo6.redis.JedisClient;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.List;
@Component
public class JedisClientPool implements JedisClient {
    @Resource
    private JedisPool jedisPool;

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public String set(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        String result = jedis.set(key,value);
        jedis.close();
        return result;
    }

    @Override
    public String get(String key) {
        return null;
    }

    @Override
    public Boolean exists(String key) {
        Jedis jedis = jedisPool.getResource();
        Boolean exists = jedis.exists(key);
        jedis.close();
        return exists;
    }

    @Override
    public Long expire(String key, int seconds) {
        return null;
    }

    @Override
    public Long ttl(String key) {
        return null;
    }

    @Override
    public Long incr(String key) {
        Jedis jedis = jedisPool.getResource();
        Long incr = jedis.incr(key);
        jedis.close();
        return incr;
    }

    @Override
    public Long hset(String key, String field, String value) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.hset(key,field,value);
        jedis.close();
        return result;
    }

    @Override
    public String hget(String key, String field) {
        Jedis jedis = jedisPool.getResource();
        String result = jedis.hget(key,field);
        jedis.close();
        return result;
    }

    @Override
    public Long hdel(String key, String... field) {
        return null;
    }

    @Override
    public Long lpush(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        Long lpush = jedis.lpush(key, value);
        jedis.close();
        return lpush;
    }

    @Override
    public List<String> lrange(String key, Integer startIndex, Integer endIndex) {
        Jedis jedis = jedisPool.getResource();
        List<String> lrange = jedis.lrange(key, startIndex, endIndex);
        jedis.close();
        return lrange;
    }

    @Override
    public String ltrim(String key, Integer startIndex, Integer endIndex) {
        Jedis jedis = jedisPool.getResource();
        String ltrim = jedis.ltrim(key, startIndex, endIndex);
        jedis.close();
        return ltrim;
    }

    @Override
    public Long rpush(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        Long rpush = jedis.rpush(key, value);
        jedis.close();
        return rpush;
    }

    @Override
    public String lindex(String key, Integer index) {
        Jedis jedis = jedisPool.getResource();
        String lindex = jedis.lindex(key, index);
        jedis.close();
        return lindex;
    }

    @Override
    public Long lrem(String key, Integer number, String value) {
        Jedis jedis = jedisPool.getResource();
        Long lrem = jedis.lrem(key, number, value);
        jedis.close();
        return lrem;
    }
    @Override
    public Double zscore(String key, String toString) {
        Jedis resource = jedisPool.getResource();
        Double zscore = resource.zscore(key, toString);
        resource.close();
        return zscore;
    }

    @Override
    public Double zincrby(String demandBrowseNumber, int i, String toString) {
        Jedis resource = jedisPool.getResource();
        Double zincrby = resource.zincrby(demandBrowseNumber, i, toString);
        resource.close();
        return zincrby;
    }

    @Override
    public String setex(String key, Integer number, String value) {
        Jedis resource = jedisPool.getResource();
        String setex = resource.setex(key, number, value);
        resource.close();
        return setex;
    }
}

UserMapper:

@Repository
public interface UserMapper {

    ManagerUser selectUser(@Param("userName") String userName, @Param("password") String password);

}

UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo6.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.example.demo6.pojo.ManagerUser" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="phone" property="phone" jdbcType="VARCHAR" />
        <result column="qq" property="qq" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="dept" property="dept" jdbcType="VARCHAR" />
    </resultMap>
    <sql id="Base_Column_List" >
    id, user_name, phone, qq, password, dept
  </sql>
    <select id="selectUser" resultMap="BaseResultMap">
        select <include refid="Base_Column_List"/>
        from manager_user where user_name=#{userName} and password=#{password}
    </select>
   
</mapper>

redis.properties:(redis的ip和端口号)

redis.node.host=192.168.43.140
redis.node.port=6379

RedisConfiguration:

@Bean:(用java类的方式把对象交给spring容器)

@Value:springboot读取配置文件,如何读取详解:

https://blog.csdn.net/qq_43154385/article/details/85132507

package com.example.demo6.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@SpringBootConfiguration
@PropertySource(value = {"classpath:redis/redis.properties"})
public class RedisConfiguration {
    @Value("${redis.node.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.node.host}")
    private String host;
    @Value("${redis.node.port}")
    private Integer port;

    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(maxTotal);
        return poolConfig;
    }
    @Bean
    public JedisPool jedisPool(){
        JedisPoolConfig poolConfig= jedisPoolConfig();
        JedisPool pool =  new JedisPool(poolConfig,host,port);
        return pool;
    }

}

 

over!

猜你喜欢

转载自blog.csdn.net/qq_43154385/article/details/85267368
0条评论
添加一条新回复