SpringBoot、MyBatis、Shiro、Thymeleaf整合思路

    科技2024-08-11  26

    简单的阐述一下基本的整合思路,方便后面需要用的时候查找。

    创建工程导入坐标、依赖 <!-- 导入mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- spring整合mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!-- 导入thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 导入shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.6.0</version> </dependency> <!-- 导入lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.22</version> </dependency> <!-- thymeleaf整合shiro--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency> 配置 application.yml 注意mapper的扫描位置 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.demo.test.pojo spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver 创建pojo、dao、mapper、service、serviceimpl、controller

    pojo类的注解有 @Data :配置常见的get、set @AllArgsConstructor :带参数构造函数 @NoArgsConstructor: 无参数构造函数

    dao接口注意**@Mapper**注解的使用

    mapper文件的namespace命名空间只要指向dao接口

    serviceimpl类必须配置**@Service注解,有事务的添加@Transactional**

    配置shiro 自定义类ShiroCofig,添加@Configuration注解 (倒叙配置比较方便)

    ShiroFilterFactoryBean :配置拦截

    DefaultWebSecurityManager

    UserRealm 配置自定义的Realm继承AuthorizingRealm重写

    doGetAuthorizationInfo:授权

    @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //拿到当前登录的对象 Subject subject = SecurityUtils.getSubject(); User user = (User)subject.getPrincipal(); //添加用户权限 info.addStringPermission(user.getPerms()); return info; }

    doGetAuthenticationInfo:认证 (可以自行添加盐制加密)

    @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usertoken=(UsernamePasswordToken) token; User user = userService.selectUserByName(usertoken.getUsername()); if (user==null){ return null; } //设置Session Subject current = SecurityUtils.getSubject(); Session session = current.getSession(); session.setAttribute("USER_SESSION",user); return new SimpleAuthenticationInfo(user,user.getPassword(),""); } ShiroDialect :用来整合shiro和thymeleaf 启动类 别忘了@ComponentScan的注解 @SpringBootApplication @ComponentScan(basePackages = "com.test.**") public class SpringshiroApplication { public static void main(String[] args) { SpringApplication.run(SpringshiroApplication.class, args); } }
    Processed: 0.012, SQL: 8