shiro和springMVC和redis集成

pom.xml中

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

<dependency>
<groupId>tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>5.5.23</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>

<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>6.0</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.5</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>

<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>

<!-- spring和freemarker集成 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.9</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>

web.xml中

<!-- shiro过滤器 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

applicationContext-shiro.xml中

<!-- 将shiro交由spring管理 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="unauthorizedUrl" value="/403.html"/>
<property name="FilterChainDefinitions">
<value>
/login=anon
/subLogin=anon
/**=authc
</value>
</property>
</bean>

<!-- 自定义realm -->
<bean id="realm" class="com.jinlin.realm.CustomRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="realm"/>
</bean>

<!-- shiro密码加密配置 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<property name="hashIterations" value="1"/>
</bean>

<!-- session管理 -->
<!-- <bean id="sessionManager" class="">
<property name="sessionDAO" ref="redisSessionDao"/>
</bean> -->

<!-- 自定义将session存入redis中 -->
<bean id="redisSessionDao" class="com.jinlin.session.RedisSessionDao">

</bean>

自定义realm类

package com.jinlin.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.jinlin.entity.Role;
import com.jinlin.service.RoleService;
import com.jinlin.service.UserService;

public class CustomRealm extends AuthorizingRealm {

{
super.setName("customRealm");
}

@Autowired
private UserService userService;

@Autowired
private RoleService roleService;

/*授权*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  List<Role> roleList = null;
  List<String> rnameList = new ArrayList<String>();
  try {
    roleList = roleService.queryRole();

    roleList.forEach((role)->{
      rnameList.add(role.getRname());
    });
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  simpleAuthorizationInfo.addRoles(rnameList);
  return simpleAuthorizationInfo;
}

/*认证*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String username = (String)token.getPrincipal();
    String password = null;
  try {
    password = userService.getPasswordByUsername(username);
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,password,"customRealm");
  return simpleAuthenticationInfo;
}

}

redis工具类

package com.imooc.util;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class JedisUtil {

  @Autowired
  private JedisPool jedisPool;

  //得到jedis连接
  private Jedis getResource() {
    return jedisPool.getResource();
  }

  //redis增加
  public byte[] set(byte[] key, byte[] value) {
      Jedis jedis = getResource();

    try {
      jedis.set(key, value);
      return value;
    } finally {
      jedis.close();
    }

  }
  //设置超时时间
  public void expire(byte[] key, int i) {
      Jedis jedis = getResource();

    try {
      jedis.expire(key, i);
    } finally {
      jedis.close();
    }

  }

  //redis取值
  public byte[] get(byte[] key) {
      Jedis jedis = getResource();

    try {
      byte[] value = jedis.get(key);
      return value;
    } finally {
      jedis.close();
    }
  }

  //redis删除
  public void del(byte[] key) {
      Jedis jedis = getResource();

    try {
      jedis.del(key);
    } finally {
      jedis.close();
    }

  }

  //redis模糊查询
  public Set<byte[]> keys(String SHIRO_SESSION_PREFIX) {
      Jedis jedis = getResource();
    try {
      return jedis.keys((SHIRO_SESSION_PREFIX + "*").getBytes());
    }finally {
      jedis.close();
    }
  }

}

将session存入redis的类

package com.imooc.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;

import com.imooc.util.JedisUtil;

import org.apache.shiro.util.CollectionUtils;

/**
* crud session
*/
public class RedisSessionDao extends AbstractSessionDAO {

  @Autowired
  private JedisUtil jedisUtil;

  //设置session前缀
  private final String SHIRO_SESSION_PREFIX = "imooc-session:";

  private void saveSession(Session session) {
    if (session != null &&session.getId() != null) {
      //相当于session.setAttribute(key,value)
      byte[] key = getKey(session.getId().toString());
      //将session序列化为byte数组
      byte[] value = SerializationUtils.serialize(session);
      jedisUtil.set(key,value);
      jedisUtil.expire(key,600);
    }
  }

  //得到session的key
  private byte[] getKey(String key) {
    return (SHIRO_SESSION_PREFIX + key).getBytes();
  }

  @Override  
  public void update(Session session) throws UnknownSessionException {
    saveSession(session);

  }

  @Override
  public void delete(Session session) {
    if (session == null || session.getId() == null) {
    return ;
  }
    byte[] key = getKey(session.getId().toString());
    jedisUtil.del(key);
  }  

  //从redis中得到session
  @Override
  public Collection<Session> getActiveSessions() {
    Set<byte[]> keys = jedisUtil.keys(SHIRO_SESSION_PREFIX);
    Set<Session> sessions = new HashSet<>();
    if (CollectionUtils.isEmpty(keys)) {
      return sessions;
    }
    for(byte[] key : keys) {
      //反序列化为session对象
      Session session = (Session) SerializationUtils.deserialize(jedisUtil.get(key));
      sessions.add(session);
    }

    return sessions;
  }

  @Override
  protected Serializable doCreate(Session session) {
    //生成sessionId
    Serializable sessionId = generateSessionId(session);
    //将session和sessionId捆绑
    assignSessionId(session, sessionId);
    saveSession(session);

    return sessionId;
  }

  @Override
  protected Session doReadSession(Serializable sessionId) {
    System.out.println("read session");
    if (sessionId == null) {
      return null;
    }
    byte[] key = getKey(sessionId.toString());
    byte[] value = jedisUtil.get(key);
    return (Session)SerializationUtils.deserialize(value);
  }

}

自定义sessionManager类,取值时只取一次,不重复取

package com.imooc.session;

import java.io.Serializable;

import javax.servlet.ServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

public class CustomSessionManager extends DefaultWebSessionManager {

  @Override
  protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
    Serializable sessionId = getSessionId(sessionKey);
    ServletRequest request = null;
    if(sessionKey instanceof WebSessionKey) {
      request = ((WebSessionKey)sessionKey).getServletRequest();
    }
    if(request != null && sessionId != null) {
      Session session = (Session)request.getAttribute(sessionId.toString());
    if (session != null) {
      return session;
    }
  }

  Session session = super.retrieveSession(sessionKey);
  if(request != null && sessionId != null) {
    request.setAttribute(sessionId.toString(), session);
  }
  return session;
  }
}

原文地址:https://www.cnblogs.com/jinlin-2018/p/9861267.html

时间: 2024-10-12 02:00:06

shiro和springMVC和redis集成的相关文章

shiro在springmvc里面的集成使用【转】

<dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <ar

SSM+Redis+Shiro+Maven框架搭建及集成应用

引文: 本文主要讲述项目框架搭建时的一些简单的使用配置,教你如何快速进行项目框架搭建. 技术: Spring+SpringMVC+Mybatis+Redis+Shiro+Maven            mybatis.redis都是使用spring集成 技术介绍就不再讲述了,话不多说,急忙上代码了. 1.新建Web项目使用Maven 进行项目管理 具体步骤不进行讲述.... 主要配置 web.xml 文件 1 <?xml version="1.0" encoding="

Apache-Shiro分布式环境配置(与redis集成)

原文戳我 前段时间项目要用到权限控制的相关模块,经过讨论决定采用Apache下面的Shiro开源框架进行身份校验与权限控制,因项目需部署在集群环境下,所以需要分布式的支持,故配置了Redis作为权限数据的存储,这里简单的记录下相关的配置 applicationContext-shiro.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

如何玩转最新的项目的搭配springmvc+mybatis+Redis+Nginx+tomcat+mysql

上一次完成nginx+tomcat组合搭配,今天我们就说说,这几个软件在项目中充当的角色: 要想完成这几个软件的组合,我们必须知道和熟悉应用这个框架, 一: Nginx:在项目中大多数作为反向代理服务器.其目的处理http静态页面.和分发请求给tomcat.是目前处理大量请求的解决方案. tomcat:作为处理动态页面的服务器.由Ngxin 均衡分给的请求来处理. redis:在这个里redis 处理两个重要的功能:第一,nginx分发请求给tomcat.如何保持session的同步.就是利用r

原创SpringMvc+Mybatis+Redis框架

声明: 本人提供这个 SpringMvc + Mybatis + Redis 的Demo 本着学习的态度,如果有欠缺和不足的地方,给予指正,并且多多包涵 框架运行环境: Maven版本:3.3.9 Eclipse版本:MARS.2 JDK版本:1.8 Tocat版本:8.0.36 框架结构:框架全采用maven管理 所以源码只有180KB左右要是不会Maven就请自行补习 infrastructure:项目名 main:一些顶层的封装 包括了 annotation:自定义注解 实现的类似于shi

springmvc整合redis架构搭建实例

新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 第一步: 创建maven项目: 实例pom.xml内容如下 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns

SpringMVC与Freemarker集成,配置项目全局的绝对路径

我发现网上这方面的相关内容不是很多(当然我学习的不是很深入).在开源中国上也发了一个贴子,有网友帮忙解答,下面附上解决方案,如果对大家有所帮助,我心甚慰! 首先定义一个类,继承FreeMarkerView. import org.springframework.web.servlet.view.freemarker.FreeMarkerView; import javax.servlet.http.HttpServletRequest; import java.util.Map; public 

Spring+SpringMvc+Mybatis框架集成搭建教程

一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼,网络上又没有很详细的讲解以及搭建的教程.闲来无事,我就利用空闲时间来写这样一个教程和搭建步骤,来帮助那些有问题的小伙伴,让你从此SSM搭建不再有问题. 二.教程目录 1.Spring+SpringMvc+Mybatis框架集成搭建教程一(项目创建) 2.Spring+SpringMvc+Mybat

SpringMVC+Spring4+Mybatis3集成,开发简单Web项目+源码下载

SpringMVC+Spring4+Mybatis3集成,开发简单Web项目+源码下载 这篇博文我们通过spring与Mybatis集成,开发一个简单用户增删改查的Web项目. 基本准备工作 1.安装JDK1.6以上版本,安装与配置 2.下载mybatis-3.2.0版:https://repo1.maven.org/maven2/org/mybatis/mybatis/ 3.下载mybatis-spring-1.2.1版:https://repo1.maven.org/maven2/org/m