MP实战系列(九)之集成Shiro

下面示例是在之前的基础上进行的,大家如果有什么不明白的可以参考MP实战系列的前八章

当然,同时也可以参考MyBatis Plus官方教程

建议如果参考如下教程,使用的技术为spring+mybatis plus + springmvc+jdk8+maven工程

满足这个条件可以减少不必要的麻烦,当然持久层也可以用mybatis。

只要按照如下示例来,也不会有大问题的。之前我也强调过mybatis和mybatis plus的区别主要是封装和继承,mybatis plus封装一系列增删改查的方法,但是这些封装方法都是靠继承。而mybatis的代码生成器就得逆向工程,当然,也可以通过这种方式,使用volocity或freemarker模板引擎,编写对应的模板(含xml,entity,service,serviceImpl,controller等),这种模板引擎的机制也涉及到Java的反射。

关于shiro教程,可以参考官网,也可以参考我的shiro实战系列,我的shiro实战系列主要参考张开涛先生的文档和github相关的教程

文档的话,大家可以参考:Java相关框架资料及其基础资料、进阶资料、测试资料之分享

通过该篇文章获取资料,包含视频等相关资料

张开涛先生的github系列地址如下:

https://github.com/zhangkaitao/shiro-example

张开涛先生的shiro博客文章系列地址如下:

http://jinnianshilongnian.iteye.com/blog/2049092

上述列出的,可以作为朋友们的学习参考,当然技术每时每刻不在更新,但是底层原理却是不变的。

关于shiro和Java流行框架(Spring+SpringMVC+MyBatis或SpringBoot等案例)

大家可以去github上找,或者直接去码云上借鉴。

码云上的案例都还不错,感谢开源并乐于分享的程序爱好者们。

至于博客文章,几年前的和现在的shiro相关案例,大家都可以参考借鉴。

为了不做拿来主义,我觉得有必要分享分享,即便相关的案例比较多,但是每篇博文我想都从不同的角度看待shiro。

俗话说:对于哈姆莱特,一千个读者有一千个体会。

至于原话是否如此,我也懒得百度搜索了,总而言之每个编程爱好者们对于技术,都有自己的视角。

一、导入依赖

            <!-- shiro -->
            <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        

二、自定义Realm

package com.shiro;

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.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import com.dao.UserDao;
import com.entity.UserEntity;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

      /**
     * 密码匹配凭证管理器
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 采用MD5方式加密
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        // 设置加密次数
        hashedCredentialsMatcher.setHashIterations(1024);
        return hashedCredentialsMatcher;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        info.addStringPermission("sys");

        System.out.println("开始授权");

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken=(UsernamePasswordToken) token; 

        String username=upToken.getUsername();

        String password=new String(upToken.getPassword());

        UserEntity user=new UserEntity();

        user.setLoginName(username);

        user=userDao.selectOne(user);

        System.out.println("===========");

        if(user!=null){

        if(user.getPassword().equals(password)){

        return new SimpleAuthenticationInfo(username,password,getName());

        }

        }

        throw new UnauthenticatedException();
    }

}

三、spring-shiro.xml配置文件内容

<?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:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd">

<!-- 自定义Realm -->
<bean id="myRealm" class="com.shiro.MyRealm"/>

<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>

<!-- Shiro过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login.html"/>
<!-- 权限认证失败,则跳转到指定页面 -->
<property name="unauthorizedUrl" value="/login.html"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/login.html=anon
/index.html=anon
/**=authc
</value>
</property>
</bean>

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- 开启Shiro注解 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>

四、web.xml内容

<filter>
     <filter-name>shiroFilter</filter-name>
       <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
       <init-param>
       <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
       <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
       </init-param>
   </filter>
   <filter-mapping>
           <filter-name>shiroFilter</filter-name>
           <url-pattern>/*</url-pattern>
 </filter-mapping>

五、测试相关的实体类及其DAO、Service等

UserEntity.java

package com.entity;

import java.io.Serializable;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;

@TableName("user")
public class UserEntity extends Model<UserEntity> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    @TableField("login_name")
    private String loginName;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    protected Serializable pkVal() {
        // TODO Auto-generated method stub
        return id;
    }

}

UserDao.java

package com.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.entity.UserEntity;

public interface UserDao extends BaseMapper<UserEntity>{

}

UserService.java

package com.service;

import com.baomidou.mybatisplus.service.IService;
import com.entity.UserEntity;

public interface UserService extends IService<UserEntity>{

}

UserServiceImpl.java

package com.service.impl;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dao.UserDao;
import com.entity.UserEntity;
import com.service.UserService;
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

}

UserDao.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.dao.UserDao">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.entity.UserEntity">
        <id column="id" property="id" />
        <result column="login_name" property="loginName" />
        <result column="password" property="password" />

    </resultMap>

</mapper>

 

最后,我想说的是,大家尽可能学习参照官网,毕竟官网是比较权威比较全面的。

当然,对于完全不懂不知道的,可以通过视频或者文档及入门程序达到有使用并了解的程度,然后在这个基础上多深入。当然,任何一门技术学习和使用过程中,问题总会不断的。

没关系,问题多,虽然挺操蛋的,但是越是觉得难受不爽,我想这就是上升带来的阻力和痛苦吧。就好比修仙者们,修仙的过程是痛苦的,当达到一定的程度时,就会天外飞仙,直达天堂。

哈哈,说过了。

总而言之,希望个人的小小分享,能给大家带来帮助。

原文地址:https://www.cnblogs.com/youcong/p/9240750.html

时间: 2024-07-30 12:36:08

MP实战系列(九)之集成Shiro的相关文章

MP实战系列(二)之集成swagger

其实与spring+springmvc+mybatis集成swagger没什么区别,只是之前写的太不好了,所以这次决定详细写. 提到swagger不得不提rest,rest是一种架构风格,里面有对不同的资源有不同的请求标识.例如PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH等. 对于技术的初学,最好的话还是建议去官网,官网最详细也最权威,虽然不少博客对此有挺好的解说,但还是强烈建议去官网,不要求仔仔细细阅读,至少读个大概. 对于目前,有人要问我swagger能做什么

MP实战系列(七)之集成springboot

springboot是现在比较流行的微服使用的框架,springboot本质上就是将spring+springmvc+mybatis零配置化,基本上springboot的默认配置符合我们的开发.当然有一部分还是需要自定义的. 本章不是专门讲springboot的,主要将springboot+mybatis plus是如何整合的. 一.导入pom依赖 <parent> <groupId>org.springframework.boot</groupId> <arti

MP实战系列(十二)之封装方法详解(续二)

继续MP实战系列(十一)之封装方法详解(续一)这篇文章之后. 此次要讲的是关于查询. 查询是用的比较多的,查询很重要,好的查询,加上索引如鱼得水,不好的查询加再多索引也是无济于事. 1.selectById()方法 演示示例: UserEntity user = ud.selectById(33); System.out.println(user.getEmail()); 简单的说明: 如果是在MyBatis中,需要再对应的xml编写这样的sql select column1,column2..

MP实战系列(三)之实体类讲解

首先说一句,mybatis plus实在太好用了! mybaits plus的实体类: 以我博客的用户类作为讲解 package com.blog.entity; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableLogic; imp

MP实战系列(四)之DAO讲解

说到DAO不得不提一个开发名词"三层架构",所谓的三层架构是什么呢?简单的可以概括为数据访问层,业务逻辑层,界面层(又称表现层). 这也是我们Java开发常用的手段,经常有人将三层架构和mvc模式混淆,在我看来,三层架构就是三层架构,mvc只是三层架构中的表现层中的架构,相当于在一个比较大的层面,往里面在细分,mvc细分,可分为模型,视图,控制器,在这里模型通常指数据,也可以叫JavaBean,而视图的话,这个视图就是展示给用户看的,通常用于视图的模板可以为jsp,freemarker

openstack运维实战系列(九)之cinder与glusterfs结合

1. 概述     cinder作为openstack的快存储服务,为instance提供永久的volume服务,cinder作为一种可插拔式的服务,能够支持各种存储类型,包括专业的FC存储,如EMC,NetApp,HP,IBM,huawei等商场的专业存储服务器,存储厂商只要开发对应的驱动和cinder对接即可:此外,cinder还支持开源的分布式存储,如glusterfs,ceph,sheepdog,nfs等,通过开源的分布式存储方案,能够达到廉价的IP-SAN存储.本文以glusterfs

MP实战系列(五)之封装方法讲解

mybatis plus封装的方法怎么用?以及它们对应的sql是那些sql?及其什么情况用? 这些需要说下,以下我将会将我常用的说下,不是常用的,可能提以下或者不提. 根据主键查询 UserEntity userEntity = ud.selectById(id); 上述这个没什么好说的 根据实体查询 UserEntity u = new UserEntity(); u.setEmail("[email protected]"); UserEntity u1 = ud.selectOn

MP实战系列(十三)之批量修改操作(前后台异步交互)

MyBatis的批量操作其实同MyBatis基本是一样的.并无多大区别,要说区别,除了封装的方法之外,主要就是注解方面的区别,比如@TableId.@TableField.@TableName等等区别. 示例描述: 本次描述的是批量相关的操作,主要是批量修改等操作. 项目讲解:如何批量修改开锁方式? 准备环境和IDE工具:MySQL5.7+Maven3以上+JDK8或者JDK7+SSM框架+tomcat8或者tomcat7应用服务器+Eclipse. 本文核心:主要是Controller代码和数

SCCM 2012 R2 实战系列(九)—统一部署Office

下边来说说如何部署Office,Office的部署其实相对来讲很简单,之前也介绍过统一部署Office的方法,主要依靠组策略以及OCT工具,通过SCCM部署Office同样需要OCT工具的支持,只不过区别在于我们不再需要组策略的支持.下边来看一下如何实施 实施之前请先参考制作OCT配置文件的博文 http://mxyit.blog.51cto.com/4308871/1406113 1.在软件库->概述里选择创建包 2.这里输入基本信息之后,主要是将Office的安装源位置在下边设置好 注意:我