ssm链接shiro小案例

 

目录

前言

一、shiro是什么?

二、.目录结构

java:

resources:

webapp:

三、Shiro的使用流程和思想:

shiro的使用流程:

1、使用工厂构建安全管理器

2、把当前的安全管理器绑定到线程(即securityUtils,在ssm和springboot中,容器注入的webSecurityManager 会自动完成这一步)

3、创建自定义的realm,重写认证和授权,并且将授权加入到安全管理器(SecurityManager)中。

4、书写拦截器,用来设置shiro拦截的界面,以及登录失败成功等跳转的界面;

5、如果要使用shiro的注解的话还要启动shiro的注解。

其实shiro中最主要最重要的也就是对于认证授权的重写,我们着重说一下认证授权重写的思想,在文档末尾进行配置的流程讲解;

四、具体ssm的搭建和代码的实现:

总结


 


前言

本文主要是对上一篇shiro整合的进一步优化,上一篇shiro主要是和springboot进行整合,唯一的缺点就是没有链接数据库,在此用ssm进行整合,并且连接数据库进行更好的说明

上一篇链接:https://blog.csdn.net/qq_39949910/article/details/107716301


 

一、shiro是什么?

 

二、.目录结构

了解这个工程之前我们先来看一下这个工程的目录结构,以对这个工程有一个更加好的理解:

在大的模块上,这个工程总共分为java、resources、web 三个大层次,分别对应的功能是:

java:书写java设计模式MVC中的MC和各种业务逻辑

resources: 书写各种静态文件、资源,以及配置文件等

web: 书写前台界面,也即MVC中的V,以及整个项目启动时候的一些读取配置和监听。

说完了这些大模块,我们再来看看大模块之中的小模块分别对应了什么作用和操作。

java:

controller:

顾名思义,这个包内的文件是控制器,主要用来控制页面的转发以及对请求的处理和响应数据的处理。

dao:

java设计模式中的持久层,主要用来处理和数据库的交互。

entity:

实体类,主要存放和数据库表所映射的各类实体以及自定义的工具实体。

realm:

shiro的架构的三大点中的realm(域),主要用来进行认证和授权,与数据库做交互。

ps:shiro架构的三大点有:subject(用户),securityManager(安全管理器),realm(域)

service:业务逻辑层,主要处理各种复杂的业务逻辑。

resources

mapper:对应了dao的映射文件,与mabatis有关

剩余的部分都是spring的配置文件。

webapp:

配置和界面。

三、Shiro的使用流程和思想:

其中对于一些复杂的流程在文档的最后作整理,这里只说明最主要的思想和业务逻辑。

shiro的使用流程:

1、使用工厂构建安全管理器

2、把当前的安全管理器绑定到线程(即securityUtils,在ssm和springboot中,容器注入的webSecurityManager 会自动完成这一步)

3、创建自定义的realm,重写认证和授权,并且将授权加入到安全管理器(SecurityManager)中。

注:如果在此步中要进行加密加盐,应该创建一个加密加盐对象(HasheedCredentialsMatcer),并且将此对象set进入到realm中。

4、书写拦截器,用来设置shiro拦截的界面,以及登录失败成功等跳转的界面;

5、如果要使用shiro的注解的话还要启动shiro的注解。

大致的java代码如下:

 String username = "zhangsan";
        String password = "zs";
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2,使用工厂创建安全管理器
        DefaultSecurityManager securityManager =(DefaultSecurityManager ) factory.getInstance();
        // 3,把当前的安全管理器绑定当到线的线程
        SecurityUtils.setSecurityManager(securityManager);

        //指定securityManager执行的realm
        MyRealm myRealm = new MyRealm();
        securityManager.setRealm(myRealm);
        // 4,使用SecurityUtils.getSubject得到主体对象
        Subject subject = SecurityUtils.getSubject();
        // 5,封装用户名和密码
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        // 6,得到认证
        try {
            subject.login(token);   //
            Object principal = subject.getPrincipal(); //用户信息session
            System.out.println("接受登陆成功后返回的信息:"+principal);
            System.out.println("认证通过");
        } catch (AuthenticationException e) {
            System.out.println("用户名或密码不正确");
        }

其实shiro中最主要最重要的也就是对于认证授权的重写,我们着重说一下认证授权重写的思想,在文档末尾进行配置的流程讲解;

   其实,在shiro的subject进行login方法的时候,就会去调用realm中的doGetAuthenticationInfo(认证)和doGetAuthorizationInfo(授权)方法,在这里

doGetAuthenticationInfo的作用主要就是将用户在前台输入的账号和密码拿过来进行验证,这个方法的返回值是一个AuthenticationInfo类型的数据这个接口的实现类为SimpleAuthenticationInfo,他有一个四个参数的构造函数:

public SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName)

分别对应了用户session,加密密码,盐值,当前类名四个数据。

用户session主要就是存放一些标记共有的数据,比如返回给前台的数据,登陆成功后的回应等,在此处我们用来存放用户登录后数据库内的权限和角色。因为在用户登录和界面操作中,认证的方法只会调用一次,而权限鉴权的操作则会执行很多次,一般来说一个用户登录后,他的角色和权限在他登录期间是不会变化的,所以如果把链接数据库查询用户的权限和角色放在授权方法中去执行就会增加数据库的负担,放在认证中,只执行一次并放在shiro的用户sesion中,当授权的时候,我们只去调用用户session中拿数据即可,这样就极大的缓解了数据库的压力。

具体的代码如下:


public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @Override
    // 授权 在这里就是将认证得到的各类权限和角色信息拿到并且返回,因为认证只会执行一次,而授权再每一次页面的鉴权中
    // 都会执行一次,为了提高效率,所以将角色和权限的获取放到认证中执行,这样可以减少与数据库的交互虽然没有

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        AcrivierUser acrivierUser= (AcrivierUser) principalCollection.getPrimaryPrincipal();
        List<String> roles=acrivierUser.getRoles();
        List<String> primessions=acrivierUser.getPermissions();
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        if (roles!=null&&roles.size()>0){
           simpleAuthorizationInfo.addRoles(roles);
        }
        if (primessions!=null&&primessions.size()>0) {
            simpleAuthorizationInfo.addStringPermissions(primessions);
        }
        return simpleAuthorizationInfo;
    }

    @Override
    // 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username =authenticationToken.getPrincipal().toString();
        User user=userService.queryUserByUserName(username);
        if (user!=null){
            List<String> roles=roleService.queryRolesByUserId(user.getUserid());
            List<String> permissions=permissionService.queryPermissionByUserId(user.getUserid());
            AcrivierUser acrivierUser=new AcrivierUser(user,roles,permissions);
//            acrivierUser 的作用是存储用户的权限和角色 ,而SimpleAuthenticationInfo里边第一个参数principal也正是这么用的。
//            Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName
            ByteSource byteSource=ByteSource.Util.bytes(user.getUsername()+user.getAddress());
            SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(acrivierUser,user.getUserpwd(),byteSource,this.getName());
            return authenticationInfo;
        }

        return null;
    }
}

其中,用来存放用户的权限和角色的数据类型实体如下:

@Data
@NoArgsConstructor
@AllArgsConstructor
// 这个 类的作用就是将所有的权限和角色装成一个类,减少鉴权的时候与数据库的交互
public class AcrivierUser {
    private User user;
private List<String> roles;
private List<String> permissions;
}

这样,再去鉴权的时候只调用一次就可以完成所有的操做。

 

四、具体ssm的搭建和代码的实现:

对于链接数据库和mvc在此就不着重进行介绍,只介绍关键的配置和代码:

书写实体:

书写dao和service:

书写mapper:

在这里贴一下代码:

 

permissionmapper:

<?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.jkt.dao.PermissionMapper">
  <resultMap id="BaseResultMap" type="com.jkt.entity.Permission">
    <id column="perid" jdbcType="INTEGER" property="perid" />
    <result column="pername" jdbcType="VARCHAR" property="pername" />
    <result column="percode" jdbcType="VARCHAR" property="percode" />
  </resultMap>
  <sql id="Base_Column_List">
    perid, pername, percode
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from permission
    where perid = #{perid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from permission
    where perid = #{perid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.jkt.entity.Permission">
    insert into permission (perid, pername, percode
      )
    values (#{perid,jdbcType=INTEGER}, #{pername,jdbcType=VARCHAR}, #{percode,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.jkt.entity.Permission">
    insert into permission
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="perid != null">
        perid,
      </if>
      <if test="pername != null">
        pername,
      </if>
      <if test="percode != null">
        percode,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="perid != null">
        #{perid,jdbcType=INTEGER},
      </if>
      <if test="pername != null">
        #{pername,jdbcType=VARCHAR},
      </if>
      <if test="percode != null">
        #{percode,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.jkt.entity.Permission">
    update permission
    <set>
      <if test="pername != null">
        pername = #{pername,jdbcType=VARCHAR},
      </if>
      <if test="percode != null">
        percode = #{percode,jdbcType=VARCHAR},
      </if>
    </set>
    where perid = #{perid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.jkt.entity.Permission">
    update permission
    set pername = #{pername,jdbcType=VARCHAR},
      percode = #{percode,jdbcType=VARCHAR}
    where perid = #{perid,jdbcType=INTEGER}
  </update>
  
  <!-- 根据用户ID查询权限 -->
  <select id="queryPermissionByUserId" resultMap="BaseResultMap">
  	select distinct t1.* from permission t1 inner join role_permission 
  	t2 inner join user_role t3
  	on(t1.perid=t2.perid and t2.roleid=t3.roleid) 
  	where t3.userid=#{value}
  </select>
</mapper>

RoleMapper:

<?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.jkt.dao.RoleMapper">
  <resultMap id="BaseResultMap" type="com.jkt.entity.Role">
    <id column="roleid" jdbcType="INTEGER" property="roleid" />
    <result column="rolename" jdbcType="VARCHAR" property="rolename" />
  </resultMap>
  <sql id="Base_Column_List">
    roleid, rolename
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from role
    where roleid = #{roleid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from role
    where roleid = #{roleid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.jkt.entity.Role">
    insert into role (roleid, rolename)
    values (#{roleid,jdbcType=INTEGER}, #{rolename,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.jkt.entity.Role">
    insert into role
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="roleid != null">
        roleid,
      </if>
      <if test="rolename != null">
        rolename,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="roleid != null">
        #{roleid,jdbcType=INTEGER},
      </if>
      <if test="rolename != null">
        #{rolename,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.jkt.entity.Role">
    update role
    <set>
      <if test="rolename != null">
        rolename = #{rolename,jdbcType=VARCHAR},
      </if>
    </set>
    where roleid = #{roleid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.jkt.entity.Role">
    update role
    set rolename = #{rolename,jdbcType=VARCHAR}
    where roleid = #{roleid,jdbcType=INTEGER}
  </update>
  
  <!-- 根据用户名查询角色 -->
  <select id="queryRolesByUserId" resultMap="BaseResultMap" >
  	select t1.* from role t1 inner join user_role t2 on(t1.roleid=t2.roleid)
  	where t2.userid=#{value}
  </select>
</mapper>

UserMapper:

<?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.jkt.dao.UserMapper">
  <resultMap id="BaseResultMap" type="com.jkt.entity.User">
    <id column="userid" jdbcType="INTEGER" property="userid" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="userpwd" jdbcType="VARCHAR" property="userpwd" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="address" jdbcType="VARCHAR" property="address" />
  </resultMap>
  <sql id="Base_Column_List">
    userid, username, userpwd, sex, address
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where userid = #{userid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where userid = #{userid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.jkt.entity.User">
    insert into user (userid, username, userpwd, 
      sex, address)
    values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{userpwd,jdbcType=VARCHAR}, 
      #{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.jkt.entity.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userid != null">
        userid,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="userpwd != null">
        userpwd,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="address != null">
        address,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userid != null">
        #{userid,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="userpwd != null">
        #{userpwd,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.jkt.entity.User">
    update user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="userpwd != null">
        userpwd = #{userpwd,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      </if>
    </set>
    where userid = #{userid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.jkt.entity.User">
    update user
    set username = #{username,jdbcType=VARCHAR},
      userpwd = #{userpwd,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR}
    where userid = #{userid,jdbcType=INTEGER}
  </update>
  
  <!-- 根据用户名查询用户 -->
   <select id="queryUserByUserName" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where username=#{username}
  </select>
</mapper>

配置文件application-dao的配置:主要用来处理数据库的操作

<?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"
       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">
<!-- 读取配置文件-->
    <context:property-placeholder location="classpath:db.properties" ></context:property-placeholder>

    <!-- 声明数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="password" value="${password}"></property>
        <property name="username" value="${user}"></property>

    </bean>
    <!--SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
       <property name="basePackage" value="com.jkt.dao"></property>
   </bean>


</beans>

application-service配置文件:在这里处理事务的配置

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

    <context:component-scan base-package="com.jkt.service"></context:component-scan>
    <!-- 事务管理类-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务的传播特性-->
    <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="reset*" propagation="REQUIRED"/>
            <tx:method name="change*" propagation="REQUIRED"/>
            <tx:method name="*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
<!-- 配置aop-->

    <aop:config>
        <aop:pointcut  expression="execution(* com.jkt.service.impl.*.*(..))" id="pc"/>
        <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="pc"></aop:advisor>
    </aop:config>




</beans>

application-shiro的配置:配置加密算法的注入,realm的注入,拦截器的书写,主要就是根据之前的java代码来配置

<?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"
       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">
<!-- 配置MD5
加密算法以及参数-->
    <bean  id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
     <property name="hashAlgorithmName" value="md5"></property>
        <property name="hashIterations" value="2"></property>
    </bean>
 <!--将MD5 算法加入到自定义的realm中 -->
<bean id="userRealm" class="com.jkt.realm.UserRealm">
    <property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
    <!--配置securiityManager对象    -->
  <bean id="defaultWebSecurityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="userRealm"></property>
 </bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
        <!-- 注入安全管理器 -->
        <property name="securityManager" ref="defaultWebSecurityManager"></property>
        <!-- 注入未登陆的跳转页面 默认的是webapp/login.jsp-->
        <property name="loginUrl" value="/index.jsp"></property>
        <!-- 注入未授权的访问页面 -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
        <!-- 配置过滤器链 -->
        <property name="filterChainDefinitions">
            <value>
                /index.jsp*=anon
                <!-- 放行跳转到登陆页面的路径 -->
                /login/toLogin*=anon
                <!-- 放行登陆的请求 -->
                /login/login*=anon
                <!-- 设置登出的路径 -->
                /login/logout*=logout
                <!-- 设置其它路径全部拦截 -->
                /**=authc
            </value>
        </property>
    </bean>






</beans>

springmvc的配置:

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		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-4.3.xsd">   <!-- 扫描 -->
    <context:component-scan base-package="com.jkt.controller"></context:component-scan>
    <!-- 配置适配器和映射器 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/view/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 配置文件上传 -->
    <!-- 配置拦截器 -->
    <!-- 配置静态资源放行-->
    <mvc:default-servlet-handler/>
 <!--   <mvc:default-servlet-handler/>
    &lt;!&ndash; 启动Shrio的注解 &ndash;&gt;-->
    <bean id="lifecycleBeanPostProcessor"
          class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    <bean
            class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
            depends-on="lifecycleBeanPostProcessor" />
    <bean
            class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="defaultWebSecurityManager" />
    </bean>


</beans>

application-Context的配置:

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

    <import resource="classpath:application-dao.xml"></import>
    <import resource="application-service.xml"></import>
    <import resource="application-shiro.xml"></import>

</beans>

web.xml文件的配置:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >



<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:application-Context.xml</param-value>
</context-param>

  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>targetBeanName</param-name>
      <param-value>shiroFilter</param-value>
    </init-param>



  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <servlet-name>springmvc</servlet-name>
  </filter-mapping>

<!--
   配置编码过滤器 开始
-->

  <!--<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <servlet-name>springmvc</servlet-name>
  </filter-mapping>-->
<!--
   配置编码过滤器 结束
-->


  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>








  <!-- 配置spring的监听器加载 applicationContext.xml结束 -->

  <!-- 配置前端控制器开始 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 注入springmvc.xml -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:springmvc.xml</param-value>
    </init-param>
    <!-- 启动创建 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

前台的Login控制器的书写:

/**
	 * 跳转到登陆页面
	 */
	@RequestMapping("toLogin")
	public String toLogin() {
		return "login";
	}

	@RequestMapping("login")
	public String login(String username, String pwd) {
		System.out.println(username+"99999999"+pwd);
		UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return "list";
		} catch (Exception e) {
			// TODO: handle exception
			return "redirect:/index.jsp";
		}

	}

}

主界面的书写:


@Controller
@RequestMapping("user")
public class UserController {

	/**
	 * 跳转到用户管理的页面
	 */
	@RequestMapping("toUserManager")
	public String toUserManager() {
		return "list";
	}

	@RequestMapping("query")
	@ResponseBody
	@RequiresPermissions("user:query")//shiro的注解,主要就是判断是否有这个权限,每次都要//验证一下
	public Map<String,Object> query(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("msg", "query");
		return map;
	}
	@RequestMapping("add")
	@ResponseBody
	@RequiresPermissions("user:add")
	public Map<String,Object> add(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("msg", "add");
		return map;
	}
	@RequiresPermissions("user:update")
	@RequestMapping("update")
	@ResponseBody
	public Map<String,Object> update(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("msg", "update");
		return map;
	}

	@RequiresPermissions("user:delete")
	@RequestMapping("delete")
	@ResponseBody
	public Map<String,Object> delete(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("msg", "delete");
		return map;
	}

	@RequiresPermissions("user:export")
	@RequestMapping("export")
	@ResponseBody
	public Map<String,Object> export(){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("msg", "export");
		return map;
	}


}

pom文件:

  <properties>
    <servlet.version>3.1.0</servlet.version>
    <jsp.version>2.3.1</jsp.version>
    <spring.version>4.3.24.RELEASE</spring.version>
    <mybatis.version>3.5.1</mybatis.version>
    <mybatis.spring.version>2.0.1</mybatis.spring.version>
    <mysql.version>5.1.47</mysql.version>
    <pagehelper.version>5.1.10</pagehelper.version>
    <druid.version>1.1.19</druid.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.7.26</slf4j.version>
    <jackson.version>2.9.9</jackson.version>
    <shiro.version>1.4.1</shiro.version>
  </properties>

  <dependencies>
  <!--servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${servlet.version}</version>
    <scope>provided</scope>
  </dependency>
  <!-- javax.servlet.jsp -->
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>${jsp.version}</version>
    <scope>provided</scope>
  </dependency>


  <!--spring-core -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <!-- mybatis -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-test</artifactId>

      <version>4.3.7.RELEASE</version>

      <scope>test</scope>

    </dependency>

  <!-- mybatis-spring -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${mybatis.spring.version}</version>
  </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
      <optional>true</optional>
    </dependency>

  <!-- mysql-connector-java -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
  </dependency>

  <!-- pagehelper -->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>${pagehelper.version}</version>
  </dependency>

  <!-- druid -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid.version}</version>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <!-- slf4j-api -->
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <!-- jackson-core -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>

  <!-- 引入shiro的包 -->
  <!-- <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
  </dependency> -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>${shiro.version}</version>
  </dependency>
</dependencies>

总结

建议根据上一篇的链接综合观看https://blog.csdn.net/qq_39949910/article/details/107716301

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值