文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

ssm整合shiro使用详解

2024-04-02 19:55

关注

这里有详细的ssm整合shiro步骤,需要先搭建ssm框架,教程在
https://www.jb51.net/article/195130.htm

整合shiro:

1.在pom.xml中引入依赖


<!--  shiro -->
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.6.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>1.6.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.6.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.6.0</version>
    </dependency>

2.新建并配置缓存ehcache.xml

在这里插入图片描述


<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>
    
    <cache name="authorizationCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <cache name="authenticationCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <cache name="shiro-activeSessionCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        />

    <!-- Place configuration for your caches following -->

</ehcache>

3.在spring配置文件applicationContext.xml配置shiro

在这里插入图片描述


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- spring 配置文件  主要配置和业务逻辑有关的 -->
    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <!-- 数据源 -->
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <context:component-scan base-package="com.liuzhan">
        <!-- 不能扫描控制器 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>


    <!-- 配置和mybatis的整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis 全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <!-- 指定mybatismapper文件的位置 -->
<!--        <property name="mapperLocations" value="classpath:mapper
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        String uName = principalCollection.getPrimaryPrincipal().toString() ;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        List<Users> list=userService.loginCheck(uName);
        //查询当前用户的角色,放在roleName中
        Set<String> roleName = new HashSet<>();
        roleName.add(list.get(0).getRole());

        //查询角色具有的权限,放在permissions中
        Set<String> permissions = new HashSet<>();
        permissions.add("manage other users");

        //把角色和权限放在授权类的对象中
        info.addRole(list.get(0).getRole());
        info.addStringPermission("manage other users");

        System.out.println("当前用户角色:"+info.getRoles());
        return info;
    }




    //认证
    //用户输入用户名和密码后,在controller调用login(token),进行认证,这边通过用户名查询密码
    //和token中用户名和密码进行比对,成功认证或失败
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("开始登录认证");

        //获取用户名,去数据库取对应密码
        String uName = (String) authenticationToken.getPrincipal();
        List<Users> list=userService.loginCheck(uName);

        if(list.size()>0){
            System.out.println("用户存在");
            String uPwd=list.get(0).getuPwd();
            // 用户名存在,去数据库中去获取密码
            // 然后和token的用户名和密码对比
            // 第三个参数是选择realm,当有多个自定义realm时有用
            SimpleAuthenticationInfo info=new
                    SimpleAuthenticationInfo(uName, uPwd, "ShiroRealm");
            return info;
        }
        else{
            System.out.println("用户不存在");
            return null;
        }

    }
}

5.controller中相关代码

在这里插入图片描述


package com.liuzhan.controller;

import com.liuzhan.entity.Users;
import com.liuzhan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;



@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String loginCheck(Users users){

        Subject subject=SecurityUtils.getSubject();
        if(!subject.isAuthenticated()) {
            UsernamePasswordToken token=new UsernamePasswordToken(users.getuName(),users.getuPwd());
            token.setRememberMe(true);
            try {
                //执行登录,会调用认证方法,如果认证失败,会抛出异常,执行catch
                subject.login(token);
            } catch (AuthenticationException e) {
                // TODO Auto-generated catch block
                System.out.println("登录失败:"+e.getMessage());
                return "login";
            }
        }
        //login(token)认证成功会执行这些语句
        System.out.println("登录成功");

        //这里如果直接 return "WEB-INF/jsp/index"的话,由于默认转发,地址栏不变,还是http://localhost:8080/ssm_shiro_war_exploded/login
        //仍然执行/login = anon过滤规则,不会执行下面的权限验证过滤规则 /**=user,roles[admin]

        //因此需要使用重定向"redirect:index",才能让 /**=user,roles[admin]过滤规则生效
        return "redirect:index";
    }

    @RequestMapping("/index")
    public String index() {
       return "WEB-INF/jsp/index";
    }
}

在这里插入图片描述

在这里插入图片描述

这里到dao service entity就不再粘贴代码了

6.数据库连接配置相关

在这里插入图片描述


jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm-shiro?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.user=root
jdbc.password=root

applicationContext.xml

在这里插入图片描述

项目中用到的是通用mapper,实体类的类名和数据库的表名对应,实体类的属性和数据库表的字段名对应

在这里插入图片描述

测试

运行项目

在这里插入图片描述

因为我shiro过滤链配置的是只有角色为admin的能进首页,角色为user不能进首页,会被拦截(数据库jake为admin,tom为user)

在这里插入图片描述

运行结果:

在这里插入图片描述

在这里插入图片描述

到此这篇关于ssm整合shiro使用详解的文章就介绍到这了,更多相关ssm整合shiro内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯