SpringBoot整合Shiro 三:整合Mybatis
搭建环境见: SpringBoot整合Shiro 一:搭建环境
shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类
整合Mybatis
添加Maven依赖
mysql、druid、mybatis
lombok是可选项,方便写实体类
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <optional>true</optional> </dependency>
实体类
User
package com.zy.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; }
数据库
application.properties
配置mybatis
mybatis.type-aliases-package=com.zy.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
Mapper
UserMapper
package com.zy.mapper; import com.zy.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Mapper @Repository public interface UserMapper { User queryUserByName(String name); }
UserMapper.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.zy.mapper.UserMapper"> <select id="queryUserByName" parameterType="String" resultType="User"> select * from user where name=#{name}; </select> </mapper>
service
UserService
package com.zy.service; import com.zy.pojo.User; public interface UserService { User queryUserByName(String name); }
UserServiceImpl
package com.zy.service; import com.zy.mapper.UserMapper; import com.zy.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); } }
UserRealm
因为整合了Mybatis,所以使用数据库来进行认证
AuthenticationInfo
//认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthenticationInfo"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; //用户名+密码 User user = userService.queryUserByName(token.getUsername()); if (user == null) { return null; } //密码认证,shiro做 return new SimpleAuthenticationInfo("", user.getPwd(), ""); }
controller不用变
测试
登录
成功
存在安全隐患,后续可以通过加密操作保障安全