1.创建一个springboot项目
选中web和thymeleaf
1.1新建index.html
Title
首页
1.2创建一个controller
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
}
一定要记住shiro的三大对象
1.subject:用户
2.SecurityManager:管理所有用户
3.Realm:连接数据
1.3导入整合用的依赖包
org.apache.shiro
shiro-spring
1.4.1
1.4创建一个config(ShiroConfig),并编写他
package com.yao.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
//DefaultWebSecurityManager
//创建 realm 对象,这个realm对象需要自定义
}
1.5创建自己的一个realmconfig,也就是在config中创建另外一个配置类UserRealm
package com.yao.config;
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.PrincipalCollection;
//自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权。。。");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证。。。");
return null;
}
}
1.6将UserRealm注册到ShiroConfig里面去,是我们自己写的这个类被spring托管
1.7新建两个测试页面并重新写一下index页面
add.html
Title
add
update.html
Title
update
index.html
Title
首页
add | update
1.8编写controller层
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
}
1.9添加过滤器
还是在shiroconfig中加入:
//添加Shiro的内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证了才能通过
user:必须拥有记住我功能才能用
perms:拥有对某个资源的权限才可以访问
role:拥有某个角色权限才能访问
*/
Map filterMap = new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
return bean;
这里希望没有认证就从add和update跳到login页面因此还要写一个login页面和改写controller
controller层:
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
login页面:
登录
1.10上面已经完成了页面拦截的功能接下来实现用户认证的工作
login.html:
登录
controller:
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据(令牌),这里是存在全局里面,都可以调的到
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);// 执行登陆的方法,如果没有异常就ok了
return "index";
} catch (UnknownAccountException e) {
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e){
model.addAttribute("msg"," 密码错误");
return "login";
}
}
UserRealm:
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证。。。");
//用户名,密码 数据库中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){
return null;//它这里会自动抛出前面的用户名错误的异常
}
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",password,"");
}
}
直接测试即可发现以上功能基本实现。
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
}
2.springboot整合mybatis
2.1导入依赖
mysql
mysql-connector-java
log4j
log4j
1.2.17
com.alibaba
druid
1.1.12
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.0
2.2编写配置文件application.yml
spring:
datasource:
username: root
password: 892095368llq
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/yao?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.3编写配置文件application.properties并新建mapper文件夹
application.properties
mybatis.type-aliases-package=com.yao.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
2.4创建pojo层,并配置lombok
org.projectlombok
lombok
1.16.10
编写一个User.java
package com.yao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
2.4创建mapper层,并写出相对应的mapper接口和resources中的对应的mapper实现
UserMapper接口
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
mapper。xml
UserService.interface
package com.yao.service;
import com.yao.pojo.User;
public interface UserService {
public User queryUserByName(String name);
}
UserServiceImpl.java
package com.yao.service;
import com.yao.mapper.UserMapper;
import com.yao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
2.6在test中测试
package com.yao;
import com.yao.service.UserService;
import com.yao.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
UserServiceImpl userService;
@Test
void contextLoads() {
System.out.println(userService.queryUserByName("幺幺"));
}
}
测试成功,继续写
2.7更改UserRealm
package com.yao.config;
import com.yao.pojo.User;
import com.yao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权。。。");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证。。。");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){
return null;
}
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
2.8添加密码加密
//还有一个md5加密,集成了hashcode是不可逆的
//比如你的密码是123456
// md5(123456,32) = e10adc3949ba59abbe56e057f20f883e
// md5(123456,16) = 49ba59abbe56e057
//MD5盐值加密e10adc3949ba59abbe56e057f20f883eusername
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
2.9请求授权实现
==============
2.10绑定thymeleaf
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
推荐阅读
看完三件事
如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
关注公众号 『 Java斗帝 』,不定期分享原创知识。
同时可以期待后续文章ing