SpringBoot整合shiro环境搭建
1)在原来的项目基础上,新建一个springboot模块


2)导入thymeleaf依赖:
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3)测试保证环境没问题:

index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
</body>
</html>
MyController:
@Controller
public class MyController {
//跳转到首页
@RequestMapping({"/", "/index","index.html"})
public String toIndex(Model model){
model.addAttribute("msg","Hello!Shiro!");
return "index";
}
}

4)整合shiro
- 1.导入shiro整合spring的包
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.8.0</version>
</dependency>
- 2.目录

- 3.配置Shiro
ShiroConfig:
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("dwsm") DefaultWebSecurityManager sm){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(sm);
return bean;
}
//DefaultWebSecurityManager
//@Qualifier("userRealm") UserRealm userRealm这里的意思是:使得这里的userRealm与spring容器中的beanid="userRealm"的bean对象绑定
@Bean(name = "dwsm") //这里加上(name = "dwsm")之后,组件名就由原来的getDefaultWebSecurityManager变为dwsm
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建 realm 对象 需要自定义一个类UserRealm
//这里的@Bean是给spring容器添加组件,并且返回类型UserRealm即为组件类型,该组件的id=“userRealm”即方法名
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
自定义一个UserRealm继承AuthorizingRealm
//自定义的realm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权doGetAuthorizationInf");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证doGetAuthorizationInf");
return null;
}
}
- 4.前端页面
add.html:
<h1>add</h1>
update.html:
<h1>update</h1>
index.html:
<h1>首页</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a>
- 5.MyController:
@Controller
public class MyController {
//跳转到首页
@RequestMapping({"/", "/index","index.html"})
public String toIndex(Model model){
model.addAttribute("msg","Hello!Shiro!");
return "index";
}
@RequestMapping("/user/add")
public String toAdd() {
return "user/add";
}
@RequestMapping("/user/update")
public String toUpdate() {
return "user/update";
}
}

浙公网安备 33010602011771号