码迷,mamicode.com
首页 > 编程语言 > 详细

shiro和springMVC和redis集成

时间:2018-10-27 15:21:51      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:工具类   ons   ebs   模糊查询   1.3   设置   getpass   bcp   fas   

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;
  }
}

 

shiro和springMVC和redis集成

标签:工具类   ons   ebs   模糊查询   1.3   设置   getpass   bcp   fas   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!