SpringBoot企业级文件管理系统实战:Shiro+Mybatis深度整合

🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

SpringBoot企业级文件管理系统实战:Shiro+Mybatis深度整合

一、引言

在企业级应用开发中,文件管理系统是一个常见且重要的模块。Spring Boot 作为当下流行的 Java 开发框架,以其快速开发、简化配置等特点备受青睐。而 Shiro 是一个强大且易用的 Java 安全框架,可用于身份验证、授权、加密等功能;MyBatis 则是一款优秀的持久层框架,能帮助我们高效地与数据库进行交互。本文将详细介绍如何使用 Spring Boot 构建一个企业级文件管理系统,并深度整合 Shiro 和 MyBatis。

二、项目环境搭建

2.1 创建 Spring Boot 项目

我们可以使用 Spring Initializr(https://start.spring.io/)来快速创建一个 Spring Boot 项目。在创建项目时,添加以下依赖:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver
  • Shiro Spring
  • MyBatis Framework

2.2 配置数据库连接

application.properties 中配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/file_management?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

2.3 配置 MyBatis

application.properties 中添加 MyBatis 相关配置:

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.filemanagement.entity

三、数据库设计

3.1 用户表(user)

字段名类型描述
idint用户 ID,主键
usernamevarchar(50)用户名
passwordvarchar(100)用户密码
rolevarchar(20)用户角色

3.2 文件表(file)

字段名类型描述
idint文件 ID,主键
file_namevarchar(200)文件名
file_pathvarchar(500)文件路径
user_idint上传用户 ID,外键关联 user 表的 id

3.3 创建表的 SQL 语句

-- 创建用户表
CREATE TABLE user (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(100) NOT NULL,
    role VARCHAR(20) NOT NULL
);

-- 创建文件表
CREATE TABLE file (
    id INT AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(200) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    user_id INT,
    FOREIGN KEY (user_id) REFERENCES user(id)
);

四、Shiro 配置与整合

4.1 创建 Shiro 配置类

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager(UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login", "anon");
        chainDefinition.addPathDefinition("/unauthorized", "anon");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }
}

4.2 创建自定义 Realm

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        User user = userService.findByUsername(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRole(user.getRole());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        String username = userToken.getUsername();
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
    }
}

五、MyBatis 整合与开发

5.1 创建实体类

public class User {
    private Integer id;
    private String username;
    private String password;
    private String role;

    // 省略 getter 和 setter 方法
}

public class File {
    private Integer id;
    private String fileName;
    private String filePath;
    private Integer userId;

    // 省略 getter 和 setter 方法
}

5.2 创建 Mapper 接口

import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
    User findByUsername(String username);
}

@Mapper
public interface FileMapper {
    List<File> findFilesByUserId(Integer userId);
    void insertFile(File file);
}

5.3 创建 Mapper XML 文件

<!-- UserMapper.xml -->
<mapper namespace="com.example.filemanagement.mapper.UserMapper">
    <select id="findByUsername" resultType="com.example.filemanagement.entity.User">
        SELECT * FROM user WHERE username = #{username}
    </select>
</mapper>

<!-- FileMapper.xml -->
<mapper namespace="com.example.filemanagement.mapper.FileMapper">
    <select id="findFilesByUserId" resultType="com.example.filemanagement.entity.File">
        SELECT * FROM file WHERE user_id = #{userId}
    </select>
    <insert id="insertFile" parameterType="com.example.filemanagement.entity.File">
        INSERT INTO file (file_name, file_path, user_id)
        VALUES (#{fileName}, #{filePath}, #{userId})
    </insert>
</mapper>

六、文件管理系统功能实现

6.1 用户登录功能

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
            return "登录成功";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            return "用户名或密码错误";
        } catch (LockedAccountException e) {
            return "账户已锁定";
        } catch (AuthenticationException e) {
            return "认证失败";
        }
    }
}

6.2 文件上传功能

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    @Autowired
    private FileMapper fileMapper;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }
        String fileName = file.getOriginalFilename();
        String filePath = "uploads/" + UUID.randomUUID().toString() + "-" + fileName;
        try {
            file.transferTo(new File(filePath));
            Subject currentUser = SecurityUtils.getSubject();
            String username = (String) currentUser.getPrincipal();
            User user = userService.findByUsername(username);
            File fileEntity = new File();
            fileEntity.setFileName(fileName);
            fileEntity.setFilePath(filePath);
            fileEntity.setUserId(user.getId());
            fileMapper.insertFile(fileEntity);
            return "文件上传成功";
        } catch (IOException e) {
            return "文件上传失败";
        }
    }
}

6.3 文件列表展示功能

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class FileListController {

    @Autowired
    private FileMapper fileMapper;

    @GetMapping("/files")
    public List<File> getFiles() {
        Subject currentUser = SecurityUtils.getSubject();
        String username = (String) currentUser.getPrincipal();
        User user = userService.findByUsername(username);
        return fileMapper.findFilesByUserId(user.getId());
    }
}

七、总结

通过以上步骤,我们成功地使用 Spring Boot 构建了一个企业级文件管理系统,并深度整合了 Shiro 和 MyBatis。Shiro 为系统提供了安全认证和授权功能,MyBatis 则帮助我们高效地与数据库进行交互。这个系统可以作为企业级文件管理的基础框架,根据实际需求进行扩展和优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanxbl957

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值