用redis實現登入受限問題
阿新 • • 發佈:2019-01-14
如果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>密 碼:<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!