ssm添加权限实现登录过滤

此次是在上一篇博客上进行功能的添加,详情请看:https://blog.csdn.net/qq_40718312/article/details/96133329
1.
先导入jar包,在pom.xml的下添加
注意添加的位置

 <spring.security.version>5.0.1.RELEASE</spring.security.version>
		
		
		
		<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

在resources包下添加spring-security.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <security:global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"></security:global-method-security>

    <!-- 配置不拦截的资源 -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/failer.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>
    <!--
    	配置具体的规则
    	auto-config="true"	不用自己编写登录的页面,框架提供默认登录页面
    	use-expressions="false"	是否使用SPEL表达式(没学习过)
    -->
    <security:http auto-config="true" use-expressions="true">
        <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" -->
        <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>

        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login.do"
                            default-target-url="/index.jsp"
                            authentication-failure-url="/failer.jsp"
                            authentication-success-forward-url="/pages/main.jsp"/>

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!--退出并跳转到首页-->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp"></security:logout>

    </security:http>

    <!-- 切换成数据库中的用户名和密码 -->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            <!-- 配置加密的方式
            <security:password-encoder ref="passwordEncoder"/> -->
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- 配置加密类 -->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
    <!-- <bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />-->
    <!-- 提供了入门的方式,在内存中存入用户名和密码
    <security:authentication-manager>
    	<security:authentication-provider>
    		<security:user-service>
    			<security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
    		</security:user-service>
    	</security:authentication-provider>
    </security:authentication-manager>
    -->

</beans>

在web.xml中添加过滤器包

   <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2.
MySQL中添加数据表

DROP TABLE IF EXISTS `role`;
CREATE TABLE `role`  (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `roleName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `roleDesc` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `users_role`;
CREATE TABLE `users_role`  (
  `userid` int(11) NULL DEFAULT NULL,
  `roleid` int(11) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

插入数据

INSERT INTO `role` VALUES (1, 'ADMIN', 'admin');
INSERT INTO `role` VALUES (2, 'USER', 'user');

role表:
在这里插入图片描述

INSERT INTO `users_role` VALUES (1, 1);
INSERT INTO `users_role` VALUES (1, 2);
INSERT INTO `users_role` VALUES (2, 2);

users_role表:
在这里插入图片描述
修改原有的数据表userinfo的数据为
在这里插入图片描述
3.
在bean包下创建Role实体类

package com.zhongruan.bean;

public class Role {
    public Role() {
    }

    private int id;
    private String roleName;
    private String roleDesc;

    public int getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }
}

在dao包下的IUserDao中添加

 UserInfo findByUserName(String username);

并在mapper包中的UserInfoMapper.xml中添加

<select id="findByUserName" parameterType="String" resultType="com.zhongruan.bean.UserInfo">
        select * from userinfo where username=#{username}
    </select>

在dao包下创建IRoleDao并添加

package com.zhongruan.dao;

import com.zhongruan.bean.Role;

import java.util.List;

public interface IRoleDao {
    List<Role> findRoleByUserId(int id);
}

并在mapper包下创建RoleMapper.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.zhongruan.dao.IRoleDao" >

    <select id="findRoleByUserId" parameterType="int" resultType="com.zhongruan.bean.Role">
        select * from role where id  in (select roleid from users_role where userid=#{id})
    </select>
</mapper>

4.
在service包下的UserInfoServiceImpl添加

 @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userinfo=userInfoDao.findByUserName(username);
        List<Role> roles=roleDao.findRoleByUserId(userinfo.getId());
        User user=new User(userinfo.getUsername(),"{noop}"+
                userinfo.getPassword(),getAuthority(roles));
        return  user;
    }

    private Collection<? extends GrantedAuthority> getAuthority(List<Role> roles){
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for(Role role:roles){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }

5.
在UserInfoController中注释掉login,因为login功能已经在spring-security.xml中实现了

 /**
    @RequestMapping("/login.do")
    public ModelAndView login(UserInfo userInfo){
        boolean flag = userInfoService.login(userInfo);
        ModelAndView mv=new ModelAndView();
        if(flag){
            mv.setViewName("main");
        }else {
            mv.setViewName("../failer");
        }
        return mv;
    }
     */

然后在login.jsp中找到

<form action="/user/login.do" method="post">

去掉/user/login.do前面的/user,如下:

<form action="/login.do" method="post">

这样基本实现了权限的功能
6.
运行程序
在浏览器中输入http://localhost:8080/user/findAll.do
在这里插入图片描述
发现变成了http://localhost:8080/login.jsp
在这里插入图片描述
使用lisi登录
在这里插入图片描述
登录成功
在这里插入图片描述
到这里,程序运行说明权限功能已经实现了

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值