Spring Boot整合Shiro搭建权限管理系统_第1页
Spring Boot整合Shiro搭建权限管理系统_第2页
Spring Boot整合Shiro搭建权限管理系统_第3页
Spring Boot整合Shiro搭建权限管理系统_第4页
Spring Boot整合Shiro搭建权限管理系统_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Spring Boot整合Shiro搭建权限管理系统一、 Spring Boot入门1. 新建一个maven工程2. 修改pom.xml文件,添加spring boot父工程<!- 继承spring boot的默认父工程 -><!- Spring Boot 父工程 -><parent><groupId></groupId><artifactId>spring-boot-starter-parent</artifactId><version></version></parent>

2、;3. 修改默认编译的jdk版本<!- 修改默认编译jdk版本 -><java.version>1.8</java.version>4. 添加spring boot启动器(web支持)<!- web支持 -><dependency><groupId></groupId><artifactId>spring-boot-starter-web</artifactId></dependency>完整的pom.xml文件如下:<project xmlns="http:

3、//POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion></modelVersion><groupId>com.hellotomcat</groupId><arti

4、factId>springboot-shiro</artifactId><version></version><!- 继承spring boot的默认父工程 -><!- Spring Boot 父工程 -><parent><groupId></groupId><artifactId>spring-boot-starter-parent</artifactId><version></version></parent><depend

5、encies><!- web支持 -><dependency><groupId></groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!- thymeleaf -><dependency><groupId></groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></de

6、pendency></dependencies><!- 修改参数 -> <properties><!- 修改默认编译jdk版本 -><java.version>1.8</java.version><!- 修改thymeleaf的版本 -><thymeleaf.version></thymeleaf.version><thymeleaf-layout-dialect.version></thymeleaf-layout-dialect.version><

7、/properties></project>5. 编写controller(UserController)package com.hellotomcat.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseB

8、ody;Controllerpublic class UserController /* * 测试方法 * return */RequestMapping("/hello")ResponseBody / 返回json数据public String hello() System.out.println("hello spring boot");return "ok"/* * 测试thymeleaf * param model * return */RequestMapping("/testThymeleaf")pub

9、lic String testThymeleaf(Model model) / 把数据放入modelmodel.addAttribute("name", "admin");/ 返回test.htmlreturn "test"6. 编写启动类Applicationpackage com.hellotomcat;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplicati

10、on;/* * Spring Boot启动类 * author Lenovo * */SpringBootApplicationpublic class Application public static void main(String args) SpringApplication.run(Application.class, args);7. 运行启动类Application(和运行普通的Java程序一样)8. 然后在浏览器输入:http:/localhost:8080/hello,就可以正常访问了,出现如下画面说明启动成功二、 导入thymeleaf页面模块1. 引入thymeleaf

11、依赖<!- thymeleaf -><dependency><groupId></groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>2. 在controller当中添加如下方法:/* * 测试thymeleaf * param model * return */RequestMapping("/testThymeleaf")public String testThymeleaf(Model m

12、odel) / 把数据放入modelmodel.addAttribute("name", "admin");/ 返回test.htmlreturn "test"3. 在src/main/resources目录下面建立templates目录用来存放页面(Spting-Boot默认页面存放路径,名字不可更改)4. 在templates目录下新建test.html<!DOCTYPE html><html><head><title>测试thymeleaf的使用</title><

13、meta name="keywords" content="keyword1,keyword2,keyword3" /><meta name="description" content="this is my page" /><meta name="content-type" content="text/html; charset=UTF-8"><!-<link rel="stylesheet" type=&quo

14、t;text/css" href="./styles.css">-></head><body><h3 th:text="$name"></h3></body></html>th:text="$name"为thymeleaf语法,获取model中传过来的值5. 在浏览器访问http:/localhost:8080/testThymeleaf 进行测试.如果能够在页面上获取到值就说明成功了.此处需要注意在thymeleaf3.0以前对页面标签语法

15、要求比较严格,开始标签必须有对应的结束标签,如果没有就出现如下错误.6. 升级thymeleaf版本(修复上面的错误),在properties节点下面添加<!- 修改thymeleaf的版本 -><thymeleaf.version></thymeleaf.version><thymeleaf-layout-dialect.version></thymeleaf-layout-dialect.version>三、 Spring Boot与Shiro整合实现用户认证1. Shiro核心API类Subject: 用户主体(把操作交给Sec

16、urityManager)SecurityManager: 安全管理器(关联Realm)Realm: shiro连接数据库的桥梁2. 导入shiro与spring整合依赖<!- shiro与Spring整合依赖 -><dependency><groupId></groupId><artifactId>shiro-spring</artifactId><version></version></dependency>3. 创建自定义Realmpackage com.hellotomcat.s

17、hiro;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollec

18、tion;/* * 自定义Realm * author Lenovo * */public class UserRealm extends AuthorizingRealm/* * 执行授权逻辑 */Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) System.out.println("执行授权逻辑");return null;/* * 执行认证逻辑 */Overrideprotected AuthenticationInfo doGetAuthenti

19、cationInfo(AuthenticationToken arg0) throws AuthenticationException System.out.println("执行认证逻辑");return null;4. 编写shiro的配置类(重点)(最基础的配置类如下)package com.hellotomcat.shiro;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import

20、 org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/* * Shiro的配置类 * author Lenovo * */Configurationpublic class ShiroConfig /* * 创建ShiroFilterFactoryBean */public ShiroFilterFactoryBea

21、n getShiroFilterFactoryBean(Qualifier("securityManager")DefaultWebSecurityManager securityManager) ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();/ 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);return shiroFilterFactoryBean;/* * 创建DefaultWe

22、bSecurityManager */Bean(name="securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(Qualifier("userRealm")UserRealm userRealm) DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();/ 关联realmsecurityManager.setRealm(userRealm);return

23、securityManager;/* * 创建Realm */Beanpublic UserRealm getRealm() return new UserRealm();5. 使用shiro内置过滤器实现拦截功能1.1. 新建两个页面add.html和update.htmladd.html页面代码:<!DOCTYPE html><html><head><title>用户新增页面</title><meta name="keywords" content="keyword1,keyword2,keyw

24、ord3"><meta name="description" content="this is my page"><meta name="content-type" content="text/html; charset=UTF-8"><!-<link rel="stylesheet" type="text/css" href="./styles.css">-></head><

25、;body>用户新增</body></html>update.html页面代码:<!DOCTYPE html><html><head><title>用户更新页面</title><meta name="keywords" content="keyword1,keyword2,keyword3"><meta name="description" content="this is my page"><m

26、eta name="content-type" content="text/html; charset=UTF-8"><!-<link rel="stylesheet" type="text/css" href="./styles.css">-></head><body>用户更新</body></html>1.2. 修改test.html页面<!DOCTYPE html><html><he

27、ad><title>测试thymeleaf的使用</title><meta name="keywords" content="keyword1,keyword2,keyword3" /><meta name="description" content="this is my page" /><meta name="content-type" content="text/html; charset=UTF-8">

28、<!-<link rel="stylesheet" type="text/css" href="./styles.css">-></head><body><h3 th:text="$name"></h3><br>进入用户添加功能:<a href="add">用户添加</a><br>进入用户更新功能:<a href="update">用户更新<

29、;/a><br></body></html>1.3. 在UserController当中添加下面的方法RequestMapping("/add")/ 没有ResponseBody这个注释则返回页面,有就返回json数据public String add() return "/user/add"RequestMapping("/update")public String update() return "/user/update"1.4. 修改ShiroConfig类pack

30、age com.hellotomcat.shiro;import java.util.LinkedHashMap;import java.util.Map;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotatio

31、n.Bean;import org.springframework.context.annotation.Configuration;/* * Shiro的配置类 * author Lenovo * */Configurationpublic class ShiroConfig /* * 创建ShiroFilterFactoryBean */Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(Qualifier("securityManager")DefaultWebSecurityManager secu

32、rityManager) ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();/ 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);/ 添加Shiro内置过滤器/* * Shiro内置过滤器,可以实现权限相关的拦截 * 常用的过滤器: * anon: 无需认证(登录)可以访问 * authc: 必须认证才可以访问 * user: 如果使用rememberMe的功能可以直接访问 * perms: 该资源必须得到资源

33、权限才可以访问 * role: 该资源必须得到角色权限才可以访问 */Map<String, String> filterMap = new LinkedHashMap<String, String>();filterMap.put("/add", "authc");filterMap.put("/update", "authc");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);return shiroFilter

34、FactoryBean;/* * 创建DefaultWebSecurityManager */Bean(name="securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(Qualifier("userRealm")UserRealm userRealm) DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();/ 关联realmsecurityManager

35、.setRealm(userRealm);return securityManager;/* * 创建Realm */Bean(name="userRealm")public UserRealm getRealm() return new UserRealm();1.5. 验证拦截功能,在test页面点击超链接,如果出现以下情况,说明拦截成功1.6. 设置跳转到自定义登录页面1.6.1. 新建一个登录页面login.htmllogin.html代码如下:<!DOCTYPE html><html><head><title>登录页

36、面</title><meta name="keywords" content="keyword1,keyword2,keyword3"><meta name="description" content="this is my page"><meta name="content-type" content="text/html; charset=UTF-8"><!-<link rel="stylesheet&

37、quot; type="text/css" href="./styles.css">-></head><body>登录页面 <br></body></html>1.6.2. 在UserController当中添加如下方法:RequestMapping("/toLogin")public String toLogin() return "/login"1.6.3. 修改ShiroConfig类package com.hellotomcat.shi

38、ro;import java.util.LinkedHashMap;import java.util.Map;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.sprin

39、gframework.context.annotation.Configuration;/* * Shiro的配置类 * author Lenovo * */Configurationpublic class ShiroConfig /* * 创建ShiroFilterFactoryBean */Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(Qualifier("securityManager")DefaultWebSecurityManager securityManager) ShiroFilte

40、rFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();/ 设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);/ 添加Shiro内置过滤器/* * Shiro内置过滤器,可以实现权限相关的拦截 * 常用的过滤器: * anon: 无需认证(登录)可以访问 * authc: 必须认证才可以访问 * user: 如果使用rememberMe的功能可以直接访问 * perms: 该资源必须得到资源权限才可以访问 * role: 该资源必须得到

41、角色权限才可以访问 */Map<String, String> filterMap = new LinkedHashMap<String, String>();filterMap.put("/add", "authc");filterMap.put("/update", "authc");/ 修改默认的登录页面shiroFilterFactoryBean.setLoginUrl("/toLogin");shiroFilterFactoryBean.setFilterCha

42、inDefinitionMap(filterMap);return shiroFilterFactoryBean;/* * 创建DefaultWebSecurityManager */Bean(name="securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(Qualifier("userRealm")UserRealm userRealm) DefaultWebSecurityManager securityManager = new Default

43、WebSecurityManager();/ 关联realmsecurityManager.setRealm(userRealm);return securityManager;/* * 创建Realm */Bean(name="userRealm")public UserRealm getRealm() return new UserRealm();1.6.4. 验证,如果页面调整到自定义登录页面则成功1.7. 使用通配符简化配置,修改ShiroConfig类将filterMap.put("/add", "authc");filte

44、rMap.put("/update", "authc");修改为:filterMap.put("/testThymeleaf", "anon");filterMap.put("/*", "authc"); /此句必须放在最下面,否则将会对所有的请求进行拦截,导致不需登录也可以访问的配置均无效6. 实现用户验证(登录)操作1.1. 修改登录页面login.html<!DOCTYPE html><html><head><title>

45、登录页面</title><meta name="keywords" content="keyword1,keyword2,keyword3"><meta name="description" content="this is my page"><meta name="content-type" content="text/html; charset=UTF-8"><!-<link rel="styleshe

46、et" type="text/css" href="./styles.css">-></head><body><h3>登录</h3><h5 th:text="$msg" style="color: red"></h5><form action="login" method="post">用户名:<input type="text" name=&q

47、uot;name"/><br>密码: <input type="password" name="password"/><br><input type="submit" value="登录"/></form></body></html>1.2. 在controller当中添加方法/* * 登录逻辑处理 */RequestMapping("/login")public String login(Str

48、ing name, String password,Model model) /* * 使用Shiro编写认证操作 */ 1.获取SubjectSubject subject = SecurityUtils.getSubject();/ 2.封装用户数据UsernamePasswordToken token = new UsernamePasswordToken(name, password);/ 3.执行登录方法try subject.login(token); / 没有异常则说明登录成功return "redirect:/testThymeleaf" catch (Un

49、knownAccountException e) /e.printStackTrace();/ 登录失败:用户名不存在model.addAttribute("msg", "用户名不存在");return "login" catch (IncorrectCredentialsException e) /e.printStackTrace();/ 登录失败:密码错误model.addAttribute("msg", "密码错误");return "login"1.3. 在Shir

50、oConfig当中添加如下代码,放行登录操作filterMap.put("/login", "anon"); / 放行登录操作1.4. 编写UserRealm的认证(判断)逻辑/* * 执行认证逻辑 */Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException System.out.println("执行认证逻辑");/ 假设数据

51、库的用户名和密码String name = "admin"String password = "root"/ 编写shiro判断逻辑,判断用户名和密码是否正确/ 1.判断用户名UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;if (!token.getUsername().equals(name) / 用户名不存在return null; / 返回null时,shiro底层会抛出UnknowAccountException/ 2.判断密码return new

52、 SimpleAuthenticationInfo("", password, "");四、 整合Mybatis实现登录功能1. 导入Mybatis相关依赖,修改pom.xml文件<!- 导入mybatis相关的依赖 -><!- 数据库连接池 druid-><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version></version></d

53、ependency><!- mysql驱动 -><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!- SpringBoot的mybatis启动器 -><dependency><groupId></groupId><artifactId>mybatis-spring-boot-starter</arti

54、factId><version></version></dependency>2. 新建一个数据库,然后再新建一张数据库表,建表语句如下(数据库需要手动创建):CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(20) DEFAULT NULL, password varchar(50) DEFAULT NULL, PRIMARY KEY (id) ENGINE=InnoDB DEFAULT CHARSET=utf8;3. 在src/main/resources目录下

55、面新建perties。(位置和文件名固定)spring.datasource.driverClassName=spring.datasource.url=jdbc:mysql:/localhost:3306/db_springbootspring.datasource.username=rootspring.datasource.password=rootspring.datasource.type=mybatis.type-aliases-package=4. 编写实体类Userpackage com.hellotomcat.domain;public clas

56、s User private Integer id;private String name;private String password;public Integer getId() return id;public void setId(Integer id) this.id = id;public String getName() return name;public void setName(String name) = name;public String getPassword() return password;public void setPassword(

57、String password) this.password = password;Overridepublic String toString() return "User id=" + id + ", name=" + name + ", password=" + password + ""5. 编写查询接口package com.hellotomcat.mapper;import com.hellotomcat.domain.User;public interface UserMapper public Us

58、er findByName(String name);6. 编写UserMapper.xml映射文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//DTD Mapper 3.0/EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.hellotomcat.mapper.UserMapp

59、er"><select id="findByName" parameterType="string" resultType="user">SELECTid,NAME,PASSWORDFROMuser where name=#value</select></mapper> 7. 编写业务接口和实现接口:package com.hellotomcat.service;import com.hellotomcat.domain.User;public interface UserServi

60、ce public User findByName(String name);实现:package com.hellotomcat.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.hellotomcat.domain.User;import ;import com.hellotomcat.service.UserService;Servicepublic class UserSer

61、viceImpl implements UserService/ 注入mapper接口Autowiredprivate UserMapper userMapper;Overridepublic User findByName(String name) return userMapper.findByName(name);8. 在启动类Application当中添加mapper包扫描的注释package com.hellotomcat;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/* * Spring B

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论