在上几篇文章的基础上,实现本次案例
注意:本篇文章的实现代码在几篇文章都已经详细的讲过了,所以在此篇文章,将不再有理论知识的陈述,更过的流程,如何通过代码实现连接数据库进行认证
添加本次案例所需要的依赖
完整代码依赖:pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.9</version>
<relativePath/>
</parent>
<groupId>com.springboot_shiro</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>14</java.version>
</properties>
<!-- web环境依赖-->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- thymeleaf依赖实现数据的传递-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!-- 导入shiro与spring的集成-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
先通过idea app连接数据库idea 工具Database连接MySQL数据库
连接数据库的内容在前几篇文章都演示过了,这一篇文章则是前几篇文章的整合版,将前几篇的内容整合在一起,更好的适合我们的使用
在数据库创建一个表,存放着我们登录时验证的信息
连接数据库:数据源为Druid:application.yml
spring:
datasource:
username: demo1
password: 123
url: jdbc:mysql://localhost:3306/girls?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource
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
driver-class-name: com.mysql.cj.jdbc.Driver
连接成功后
创建pojo类,用以存放数据库的信息user.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class user {
private String username;
private String password;
}
创建mapper接口,定义数据库的具体操作,查询操作 interence UserMapper
@Repository
@Mapper
public interface UserMapper {
public user queryUser(String name);
}
创建service层
创建userService 内容与UserMapper 接口差不多,少了注解:此接口为了更好的了解
package com.springboot_shiro.service;
import com.springboot_shiro.pojo.user;
public interface userService {
public user queryUser(String name);
}
创建userService接口的实现类:
import javax.annotation.Resource;
@Service
public class userServiceimp implements userService {
@Autowired
UserMapper userMapper;
@Override
public user queryUser(String name) {
System.out.println("22");
return userMapper.queryUser(name);
}
}
创建Mapper配置文件,执行sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 映射到指定的接口-->
<mapper namespace="com.springboot_shiro.mapper.UserMapper">
<!-- 并重载接口中定义的方法-->
<select id="queryUser" resultType="user" parameterType="String">
select * from girls.login where username = #{name}
</select>
</mapper>
这里的id值为前面创建的userMapper方法,在这个配置文件执行前面的配置的方法
光通过一个id属性是没办法让xml文件知道,这里的方法那个接口中的方法,我们要用过配置文件去设置路径
mybatis.type-aliases-package=com.springboot_shiro.pojo
mybatis.mapper-locations=classpath:/mapper/*.xml
通过测试文件看能否输出从数据库中查询的数据
@SpringBootTest
class DemoApplicationTests {
@Autowired
com.springboot_shiro.service.userServiceimp userServiceimp;
@Test
void contextLoads() throws Exception{
System.out.println(userServiceimp.queryUser("demo1"));
}
}
控制台输出:
数据查询成功:与数据库的交互完成
将mybatis与shiro框架整合在一起
shiro框架
域名配置
@Controller
public class controller1 {
//索引网页的设置
@RequestMapping("/")
public String Toindex(Model model){
return "index";
}
//add网页
@RequestMapping("/add")
public String add(){
return "add";
}
//update网页
@RequestMapping("/update")
public String update(){
return "update";
}
//登录界面
@RequestMapping("/tologin")
public String login(){
return "login";
}
//登录界面form表格进行提交,提交到这
@RequestMapping("/get")
public String getword(String username,String password,Model model){
//组件一:subject
Subject subject = SecurityUtils.getSubject();
//将用用户名和密码进行加密
UsernamePasswordToken Token = new UsernamePasswordToken(username, password);
//通过subject将Token交给securitymanager进行验证
try {
subject.login(Token); //验证通过,跳转到index网页
return "index";
}
catch (UnknownAccountException e){ //出现用户名错误
model.addAttribute("msg","用户名输入错误"); //通过model类进参数的传递
return "login";
}
catch (IncorrectCredentialsException e){ //出现密码错误
model.addAttribute("msg","密码输入错误");
return "login";
}
}
}
定义shiro验证流程
package com.springboot_shiro.Myconfig;
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.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
//isAuthenticated:用于判断用户是否已经进行登录
@Configuration
public class config1 {
//定义认证流程过程中需要的程序
// shiroFilterFactoryBean组件可以实现指定网页的拦截,并为文件的访问设置权限
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager FactoryBean){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(FactoryBean);
//拦截请求
Map<String,String> map = new LinkedHashMap<>();
//权限设置:当访问/add这个网页要先进行登录
map.put("/add","authc");
//访问/update则不需要进行任何操作,直接可以进行访问
map.put("/update","anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//访问需要进行认证的网页,如果没有进行登录则进行网页的跳转
shiroFilterFactoryBean.setLoginUrl("/tologin");
return shiroFilterFactoryBean;
}
//对内部的组件进行管理
@Bean
public DefaultWebSecurityManager securityManager(@Qualifier("realm") Realm realm){
DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
SecurityManager.setRealm(realm);
return SecurityManager;
}
//用户验证的桥梁,实现用户的认证信息的确认
@Bean
public Realm realm(){
return new Realm();
}
}
前面的代码与上一篇文章相同,不需要进行更改,
但Realm则不同,他要与前面关于Mybatis配置结合在一起
public class Realm extends AuthorizingRealm {
@Autowired
com.springboot_shiro.service.userService userService;
//授权内容则是在这个接口进行配置
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权");
return null;
}
//验证则是在这个接口进行配置
//获取subject传递来的参数加密的令牌Token,进行认证
//AuthenticationInfo是一个接口:return它的的实现类
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
UsernamePasswordToken token =(UsernamePasswordToken) Token; //转换
user user = userService.queryUser(token.getUsername());
System.out.println(token.getUsername());
if (user==null){
return null;
}
//密码的验证,在spring boot架构中给一个类SimpleAuthenticationInfo可以自动化进行认证
return new SimpleAuthenticationInfo("",user.getPassword(),"");
}
}
代码完毕:执行项目进行登录
控制台输出:说明登陆成功
尝试登陆其他的用户:报错
shiro与mybatis关于认证方面整合完成