├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ ├── mapper │ │ │ ├── DictMapper.java │ │ │ ├── RoleMenuMapper.java │ │ │ ├── MenuMapper.java │ │ │ ├── RoleMapper.java │ │ │ ├── FilesMapper.java │ │ │ ├── CourseMapper.java │ │ │ └── UserMapper.java │ │ │ ├── config │ │ │ ├── AuthAccess.java │ │ │ ├── MybatisPlusConfig.java │ │ │ ├── InterceptorConfig.java │ │ │ ├── CorsConfig.java │ │ │ └── interceptor │ │ │ │ └── JwtInterceptor.java │ │ │ ├── controller │ │ │ ├── dto │ │ │ │ ├── UserPasswordDTO.java │ │ │ │ └── UserDTO.java │ │ │ ├── CourseController.java │ │ │ ├── RoleController.java │ │ │ ├── MenuController.java │ │ │ ├── EchartsController.java │ │ │ ├── FilesController.java │ │ │ └── UserController.java │ │ │ ├── model │ │ │ ├── RoleMenu.java │ │ │ ├── Dict.java │ │ │ ├── Files.java │ │ │ ├── Role.java │ │ │ ├── Course.java │ │ │ ├── Menu.java │ │ │ └── User.java │ │ │ ├── exception │ │ │ ├── ServiceException.java │ │ │ └── GlobalExceptionHandler.java │ │ │ ├── common │ │ │ ├── Constants.java │ │ │ └── Result.java │ │ │ ├── service │ │ │ ├── MenuService.java │ │ │ ├── RoleService.java │ │ │ ├── CourseService.java │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ │ ├── MenuServiceImpl.java │ │ │ │ ├── CourseServiceImpl.java │ │ │ │ ├── RoleServiceImpl.java │ │ │ │ └── UserServiceImpl.java │ │ │ ├── SpringbootFirstPracticeApplication.java │ │ │ └── utils │ │ │ └── TokenUtil.java │ └── resources │ │ ├── mapper │ │ ├── DictMapper.xml │ │ ├── RoleMenuMapper.xml │ │ ├── RoleMapper.xml │ │ ├── MenuMapper.xml │ │ ├── CourseMapper.xml │ │ ├── FilesMapper.xml │ │ └── UserMapper.xml │ │ └── application.yml └── test │ └── java │ └── com │ └── example │ ├── SpringbootFirstPracticeApplicationTests.java │ └── MyTest.java ├── .gitignore ├── README.md ├── pom.xml └── sql.sql /src/main/java/com/example/mapper/DictMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.Dict; 4 | 5 | import java.util.List; 6 | 7 | public interface DictMapper { 8 | List findAll(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/config/AuthAccess.java: -------------------------------------------------------------------------------- 1 | package com.example.config; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Target({ElementType.METHOD}) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Documented 8 | public @interface AuthAccess { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/dto/UserPasswordDTO.java: -------------------------------------------------------------------------------- 1 | package com.example.controller.dto; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class UserPasswordDTO { 7 | private String username; 8 | private String password; 9 | private String newPassword; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/RoleMenu.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableName; 4 | import lombok.Data; 5 | 6 | @TableName("sys_role_menu") 7 | @Data 8 | public class RoleMenu { 9 | 10 | private Integer roleId; 11 | private Integer menuId; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Dict.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableName; 4 | import lombok.Data; 5 | 6 | @TableName("sys_dict") 7 | @Data 8 | public class Dict { 9 | 10 | private String name; 11 | private String value; 12 | private String type; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/RoleMenuMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.RoleMenu; 4 | 5 | import java.util.List; 6 | 7 | public interface RoleMenuMapper { 8 | int deleteByRoleId(Integer id); 9 | 10 | int insert(RoleMenu roleMenu); 11 | 12 | List getByRoleId(Integer id); 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/example/SpringbootFirstPracticeApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringbootFirstPracticeApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/exception/ServiceException.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | import lombok.Getter; 4 | 5 | /** 6 | * 自定义异常 7 | */ 8 | @Getter 9 | public class ServiceException extends RuntimeException{ 10 | private String code; 11 | 12 | public ServiceException(String code,String msg){ 13 | super(msg); 14 | this.code = code; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/Constants.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | public interface Constants { 4 | String CODE_200 = "200"; //成功 5 | String CODE_500 = "500"; //系统错误 6 | String CODE_401 = "401"; //权限不足 7 | String CODE_400 = "400"; //参数错误 8 | String CODE_600 = "600"; //其他业务异常 9 | 10 | String DICT_TYPE_ICON = "icon"; 11 | 12 | String USER_ALL = "user_all"; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/MenuService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.Menu; 4 | import com.example.model.Role; 5 | 6 | import java.util.List; 7 | 8 | public interface MenuService { 9 | List findAll(String name); 10 | 11 | int saveOrUpdate(Menu menu); 12 | 13 | int removeById(Integer id); 14 | 15 | int removeByIds(List ids); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/mapper/DictMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Files.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import lombok.Data; 4 | 5 | import java.io.Serializable; 6 | 7 | @Data 8 | public class Files implements Serializable { 9 | private Integer id; 10 | private String name; 11 | private String type; 12 | private Long size; 13 | private String url; 14 | private String md5; 15 | private Boolean isDelete; 16 | private Boolean enable; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/MenuMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.Menu; 4 | import com.example.model.Role; 5 | 6 | import java.util.List; 7 | import java.util.MissingResourceException; 8 | 9 | public interface MenuMapper { 10 | List findAll(String name); 11 | 12 | int insert(Menu menu); 13 | 14 | int update(Menu menu); 15 | 16 | int removeById(Integer id); 17 | 18 | int removeByIds(List ids); 19 | 20 | Menu getById(Integer id); 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableName; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import java.io.Serializable; 8 | 9 | @Getter 10 | @Setter 11 | @TableName("sys_role") 12 | public class Role implements Serializable { 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | private Integer id; 17 | 18 | private String name; 19 | 20 | private String description; 21 | 22 | private String flag; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/dto/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.example.controller.dto; 2 | 3 | import com.example.model.Menu; 4 | import lombok.Data; 5 | import lombok.ToString; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * 接收前端登录请求的参数 11 | */ 12 | @Data 13 | @ToString 14 | public class UserDTO { 15 | 16 | private String id; 17 | 18 | private String username; 19 | 20 | private String password; 21 | 22 | private String nickname; 23 | 24 | private String token; 25 | 26 | private String role; 27 | 28 | private List menus; 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #配置数据源 2 | spring: 3 | datasource: 4 | driver-class-name: com.mysql.cj.jdbc.Driver 5 | url: jdbc:mysql://localhost:3306/你的数据库名字?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 6 | username: root 7 | password: "你的密码" 8 | jackson: 9 | date-format: yyyy-MM-dd HH:mm:ss 10 | time-zone: GMT+8 11 | 12 | #配置端口号 13 | server: 14 | port: 8081 15 | 16 | mybatis: 17 | mapper-locations: classpath:mapper/*.xml 18 | configuration: 19 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/RoleMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.Role; 4 | import com.example.model.User; 5 | 6 | import java.util.List; 7 | 8 | public interface RoleMapper { 9 | List findPage(String name, Integer pageNum, Integer pageSize); 10 | 11 | Integer findTotal(String name); 12 | 13 | int insert(Role role); 14 | 15 | int update(Role role); 16 | 17 | int removeById(Integer id); 18 | 19 | int removeByIds(List ids); 20 | 21 | List findAll(); 22 | 23 | Integer getByFlag(String flag); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/example/SpringbootFirstPracticeApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @SpringBootApplication 9 | @MapperScan("com.example.mapper") 10 | public class SpringbootFirstPracticeApplication { 11 | 12 | public static void main(String[] args) { 13 | SpringApplication.run(SpringbootFirstPracticeApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.Role; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public interface RoleService { 9 | 10 | void setRoleMenu(Integer roleId, List menuIds); 11 | 12 | List getRoleMenu(Integer roleId); 13 | 14 | Map findPage(String name, Integer pageNum, Integer pageSize); 15 | 16 | Integer saveOrUpdate(Role role); 17 | 18 | int removeById(Integer id); 19 | 20 | int removeByIds(List ids); 21 | 22 | List findAll(); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/FilesMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.Files; 4 | 5 | import java.util.List; 6 | 7 | public interface FilesMapper { 8 | 9 | int insert(Files savaFile); 10 | 11 | Files getByMd5(String md5); 12 | 13 | List selectPage(Integer pageNum,Integer pageSize,String name); 14 | 15 | int selectTotal(String name); 16 | 17 | Files selectById(Integer id); 18 | 19 | int deleteById(Integer id); 20 | 21 | int deleteBatch(List id); 22 | 23 | int updateById(Files files); 24 | 25 | List selectByIds(List id); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Course.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableName; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | import java.io.Serializable; 8 | 9 | @Getter 10 | @Setter 11 | @TableName("course") 12 | public class Course implements Serializable { 13 | 14 | private static final long serialVersionUID = 1L; 15 | 16 | private Integer id; 17 | 18 | private String name; 19 | 20 | private Integer score; 21 | 22 | private String times; 23 | 24 | private Boolean state; 25 | 26 | private Integer teacherId; 27 | 28 | private String teacher; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/CourseService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.example.model.Course; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public interface CourseService { 9 | Map findPage(String name, Integer pageNum, Integer pageSize); 10 | 11 | Integer removeById(Integer id); 12 | 13 | Integer removeByIds(List id); 14 | 15 | List findAll(); 16 | 17 | Integer saveOrUpdate(Course course); 18 | 19 | String getTeacherById(Integer id); 20 | 21 | int setStudentCourse(Integer courseId, Integer studentId); 22 | 23 | Integer update(Course course); 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/example/MyTest.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import com.example.controller.dto.UserDTO; 4 | import com.example.mapper.UserMapper; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | 8 | import javax.annotation.Resource; 9 | 10 | public class MyTest { 11 | @Resource 12 | private UserMapper userMapper; 13 | @Test 14 | public void getUserDTO(){ 15 | UserDTO userDTO = new UserDTO(); 16 | userDTO.setUsername("admin"); 17 | userDTO.setPassword("admin"); 18 | UserDTO userDTO1 = userMapper.login(userDTO); 19 | System.out.println(userDTO1); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/resources/mapper/RoleMenuMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | delete from sys_role_menu where role_id = #{id} 7 | 8 | 9 | 10 | insert into sys_role_menu (role_id,menu_id) values (#{roleId},#{menuId}) 11 | 12 | 13 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/CourseMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.example.model.Course; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public interface CourseMapper { 9 | List findPage(String name, Integer pageNum, Integer pageSize); 10 | 11 | Integer findTotal(String name); 12 | 13 | Integer removeById(Integer id); 14 | 15 | Integer removeByIds(List id); 16 | 17 | List findAll(); 18 | 19 | Integer insert(Course course); 20 | 21 | Integer update(Course course); 22 | 23 | String getTeacherById(Integer id); 24 | 25 | int setStudentCourse(Integer courseId, Integer studentId); 26 | 27 | int deleteStudentCourse(Integer courseId, Integer studentId); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | import com.example.common.Result; 4 | import org.springframework.web.bind.annotation.ControllerAdvice; 5 | import org.springframework.web.bind.annotation.ExceptionHandler; 6 | import org.springframework.web.bind.annotation.ResponseBody; 7 | 8 | @ControllerAdvice 9 | public class GlobalExceptionHandler { 10 | /** 11 | * 如果抛出的是ServiceException,则调用该方法 12 | * @param serviceException 业务异常 13 | * @return Result 14 | */ 15 | @ExceptionHandler(ServiceException.class) 16 | @ResponseBody 17 | public Result handle(ServiceException serviceException){ 18 | return Result.error(serviceException.getCode(),serviceException.getMessage()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Menu.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableField; 4 | import com.baomidou.mybatisplus.annotation.TableName; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | import java.io.Serializable; 9 | import java.util.List; 10 | 11 | @Getter 12 | @Setter 13 | @TableName("sys_menu") 14 | public class Menu implements Serializable { 15 | 16 | private static final long serialVersionUID = 1L; 17 | 18 | private Integer id; 19 | 20 | private String name; 21 | 22 | private String path; 23 | 24 | private String icon; 25 | 26 | private String description; 27 | 28 | @TableField(exist = false) 29 | private List children; 30 | 31 | private Integer pid; 32 | 33 | private String pagePath; 34 | 35 | private String sortNum; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/example/config/MybatisPlusConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.config; 2 | 3 | import com.baomidou.mybatisplus.annotation.DbType; 4 | import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; 5 | import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; 6 | import org.mybatis.spring.annotation.MapperScan; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | @MapperScan("com.example.mapper") 12 | public class MybatisPlusConfig { 13 | @Bean 14 | public MybatisPlusInterceptor mybatisPlusInterceptor() { 15 | MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); 16 | interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); 17 | return interceptor; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/Result.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | import lombok.ToString; 7 | 8 | /** 9 | * 接口统一返回包装类 10 | */ 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @ToString 15 | public class Result { 16 | private String code; 17 | private String msg; 18 | private Object data; 19 | 20 | public static Result success(){ 21 | return new Result(Constants.CODE_200,"",null); 22 | } 23 | 24 | public static Result success(Object data){ 25 | return new Result(Constants.CODE_200,"",data); 26 | } 27 | 28 | public static Result error(String code,String msg){ 29 | return new Result(code,msg,null); 30 | } 31 | public static Result error(){ 32 | return new Result(Constants.CODE_500,"系统错误",null); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | springboot+vue+mybatis等其他技术实现的学生选课后台管理系统,实现了学生选课,管理员管理用户信息,控制权限等功能 2 | 3 | 前端程序地址 https://github.com/Squirrel001202/vue.git 4 | 5 | 搭建java开发环境 6 | 导入sql.sql 7 | 在application.yml文件中配置数据库连接 8 | 登录页:/login 9 | 默认管理员账户:admin 10 | 默认管理员密码:admin 11 | 管理员添加的用户默认密码是123 12 | 部分截图: 13 | ![image](https://user-images.githubusercontent.com/105700961/174572584-bb741063-e9fc-46b5-b70e-299c90bb4d47.png) 14 | ![image](https://user-images.githubusercontent.com/105700961/174572856-1425f366-7203-4fc5-9c85-2078fd30b6c2.png) 15 | ![image](https://user-images.githubusercontent.com/105700961/174572885-3c0426e7-8007-490f-bd96-d60bdbcc7c7d.png) 16 | ![image](https://user-images.githubusercontent.com/105700961/174572910-ca169eb4-269c-442e-a48f-83c1097ddf3e.png) 17 | ![image](https://user-images.githubusercontent.com/105700961/174572984-fc328889-aba6-48b6-aaf8-20a896238689.png) 18 | ![image](https://user-images.githubusercontent.com/105700961/174573016-779386c0-bc59-48d1-a735-c24f68ccad86.png) 19 | -------------------------------------------------------------------------------- /src/main/java/com/example/config/InterceptorConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.config; 2 | 3 | import com.example.config.interceptor.JwtInterceptor; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | @Configuration 10 | public class InterceptorConfig implements WebMvcConfigurer { 11 | 12 | @Override 13 | public void addInterceptors(InterceptorRegistry registry) { 14 | registry.addInterceptor(jwtInterceptor()) 15 | .addPathPatterns("/**") // 拦截所有请求,通过判断token是否合法来决定是否需要登录 16 | .excludePathPatterns("/user/login", "/user/register","/user/export"); 17 | 18 | } 19 | 20 | @Bean 21 | public JwtInterceptor jwtInterceptor() { 22 | return new JwtInterceptor(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import cn.hutool.core.annotation.Alias; 4 | import com.baomidou.mybatisplus.annotation.TableField; 5 | import com.fasterxml.jackson.annotation.JsonIgnore; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | import lombok.ToString; 10 | 11 | import java.io.Serializable; 12 | import java.util.Date; 13 | import java.util.List; 14 | 15 | @Data 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @ToString 19 | public class User implements Serializable { 20 | private Integer id; 21 | 22 | private String username; 23 | 24 | @JsonIgnore 25 | private String password; 26 | 27 | private String nickname; 28 | 29 | private String email; 30 | 31 | private String phone; 32 | 33 | private String address; 34 | 35 | private Date createTime; 36 | 37 | private String role; 38 | 39 | @TableField(exist = false) 40 | private List courses; 41 | 42 | @TableField(exist = false) 43 | private List StuCourses; 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.example.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 4 | import com.example.controller.dto.UserDTO; 5 | import com.example.controller.dto.UserPasswordDTO; 6 | import com.example.mapper.UserMapper; 7 | import com.example.model.User; 8 | 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | public interface UserService { 13 | List selectAll(); 14 | 15 | int save(User user); 16 | 17 | int deleteById(Integer id); 18 | 19 | Map selectPage(Integer pageNum, Integer pageSize,String username,String email,String address); 20 | 21 | int selectTotal(String username,String email,String address); 22 | 23 | int deleteBatch(List id); 24 | 25 | int insertBatch(List userList); 26 | 27 | UserDTO login(UserDTO userDTO); 28 | 29 | UserDTO register(UserDTO userDTO); 30 | 31 | User getPerson(String username); 32 | 33 | User getById(String id); 34 | 35 | void updatePassword(UserPasswordDTO userPasswordDTO); 36 | 37 | List selectByRole(String role); 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.example.controller.dto.UserDTO; 5 | import com.example.controller.dto.UserPasswordDTO; 6 | import com.example.model.User; 7 | import org.apache.ibatis.annotations.Mapper; 8 | 9 | import java.util.List; 10 | 11 | //@Mapper 12 | public interface UserMapper { 13 | List selectAll(); 14 | 15 | int insert(User user); 16 | 17 | int update(User user); 18 | 19 | int deleteById(Integer id); 20 | 21 | List selectPage(Integer pageNum,Integer pageSize,String username,String email,String address); 22 | 23 | int selectTotal(String username,String email,String address); 24 | 25 | int deleteBatch(List id); 26 | 27 | int insertBatch(List userList); 28 | 29 | UserDTO login(UserDTO userDTO); 30 | 31 | UserDTO register(UserDTO userDTO); 32 | 33 | User getPerson(String username); 34 | 35 | User getById(String id); 36 | 37 | int updatePassword(UserPasswordDTO userPasswordDTO); 38 | 39 | List selectByRole(String role); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/example/config/CorsConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.cors.CorsConfiguration; 6 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 7 | import org.springframework.web.filter.CorsFilter; 8 | 9 | @Configuration 10 | public class CorsConfig { 11 | 12 | // 当前跨域请求最大有效时长。这里默认1天 13 | private static final long MAX_AGE = 24 * 60 * 60; 14 | 15 | @Bean 16 | public CorsFilter corsFilter() { 17 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 18 | CorsConfiguration corsConfiguration = new CorsConfiguration(); 19 | corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址 20 | corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 21 | corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 22 | corsConfiguration.setMaxAge(MAX_AGE); 23 | source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 24 | return new CorsFilter(source); 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/example/utils/TokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.utils; 2 | 3 | import cn.hutool.core.date.DateUtil; 4 | import cn.hutool.core.util.StrUtil; 5 | import com.auth0.jwt.JWT; 6 | import com.auth0.jwt.algorithms.Algorithm; 7 | import com.example.model.User; 8 | import com.example.service.UserService; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.context.request.RequestContextHolder; 12 | import org.springframework.web.context.request.ServletRequestAttributes; 13 | 14 | import javax.annotation.PostConstruct; 15 | import javax.servlet.http.HttpServletRequest; 16 | import java.util.Date; 17 | @Component 18 | public class TokenUtil { 19 | 20 | private static UserService staticUserService; 21 | 22 | @Autowired 23 | private UserService userService; 24 | 25 | @PostConstruct 26 | public void setUserService(){ 27 | staticUserService = userService; 28 | } 29 | /** 30 | * 生成token 31 | * @return string 32 | */ 33 | public static String genToken(String userId,String sign){ 34 | return JWT.create().withAudience(userId) //将userId保存到token里面,作为载荷 35 | .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期 36 | .sign(Algorithm.HMAC256(sign)); //以password作为token密钥 37 | } 38 | /** 39 | * 获取当前登录的用户信息 40 | * 41 | * @return user对象 42 | */ 43 | public static User getCurrentUser() { 44 | try { 45 | HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 46 | String token = request.getHeader("token"); 47 | if (StrUtil.isNotBlank(token)) { 48 | String userId = JWT.decode(token).getAudience().get(0); 49 | return staticUserService.getById(userId); 50 | } 51 | } catch (Exception e) { 52 | return null; 53 | } 54 | return null; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/impl/MenuServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service.impl; 2 | 3 | import com.example.mapper.MenuMapper; 4 | import com.example.model.Menu; 5 | import com.example.model.Role; 6 | import com.example.service.MenuService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | 14 | @Service 15 | public class MenuServiceImpl implements MenuService { 16 | 17 | @Resource 18 | private MenuMapper menuMapper; 19 | 20 | @Override 21 | public List findAll(String name) { 22 | List list = menuMapper.findAll(name); 23 | // 找出pid为null的一级菜单 24 | List parentNodes = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList()); 25 | // 找出一级菜单的子菜单 26 | for (Menu menu : parentNodes) { 27 | // 筛选所有数据中pid=父级id的数据就是二级菜单 28 | menu.setChildren(list.stream().filter(m -> menu.getId().equals(m.getPid())).collect(Collectors.toList())); 29 | } 30 | return parentNodes; 31 | } 32 | 33 | @Override 34 | public int saveOrUpdate(Menu menu) { 35 | if (menu.getId() == null) { //role没有id,表示新增,否则更新 36 | //名字,描述,唯一标识都不为空或空串 37 | if(null != menu.getName() && !("".equals(menu.getName()))){ 38 | return menuMapper.insert(menu); 39 | }else{ 40 | return 0; 41 | } 42 | } else { 43 | if(null != menu.getName() && !("".equals(menu.getName()))){ 44 | return menuMapper.update(menu); 45 | }else{ 46 | return 0; 47 | } 48 | } 49 | } 50 | @Override 51 | public int removeById(Integer id) { 52 | return menuMapper.removeById(id); 53 | } 54 | 55 | @Override 56 | public int removeByIds(List ids) { 57 | return menuMapper.removeByIds(ids); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/CourseController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import com.example.common.Constants; 4 | import com.example.common.Result; 5 | import com.example.model.Course; 6 | import com.example.service.CourseService; 7 | import com.example.service.UserService; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.List; 12 | 13 | @RestController 14 | @RequestMapping("/course") 15 | public class CourseController { 16 | 17 | @Resource 18 | private CourseService courseService; 19 | 20 | @Resource 21 | private UserService userService; 22 | 23 | // 新增或者更新 24 | @PostMapping 25 | public Result save(@RequestBody Course course) { 26 | if(courseService.saveOrUpdate(course) != 0){ 27 | return Result.success(); 28 | }else{ 29 | return Result.error(Constants.CODE_400,"名称不能为空"); 30 | } 31 | } 32 | @PostMapping("/studentCourse/{courseId}/{studentId}") 33 | public Result studentCourse(@PathVariable Integer courseId, @PathVariable Integer studentId) { 34 | courseService.setStudentCourse(courseId, studentId); 35 | return Result.success(); 36 | } 37 | 38 | @DeleteMapping("/{id}") 39 | public Result delete(@PathVariable Integer id) { 40 | courseService.removeById(id); 41 | return Result.success(); 42 | } 43 | 44 | @PostMapping("/del/batch") 45 | public Result deleteBatch(@RequestBody List id) { 46 | courseService.removeByIds(id); 47 | return Result.success(); 48 | } 49 | 50 | @GetMapping 51 | public Result findAll() { 52 | return Result.success(courseService.findAll()); 53 | } 54 | 55 | // @GetMapping("/{id}") 56 | // public Result findOne(@PathVariable Integer id) { 57 | // return Result.success(courseService.getById(id)); 58 | // } 59 | 60 | @GetMapping("/page") 61 | public Result findPage(@RequestParam String name, 62 | @RequestParam Integer pageNum, 63 | @RequestParam Integer pageSize) { 64 | return Result.success(courseService.findPage(name,pageNum,pageSize)); 65 | } 66 | @PostMapping("/update") 67 | public Result update(@RequestBody Course course) { 68 | return Result.success(courseService.update(course)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/resources/mapper/RoleMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 16 | 17 | 18 | 26 | 27 | 28 | 29 | insert into sys_role (name,description,flag) values (#{name},#{description},#{flag}) 30 | 31 | 32 | 33 | 34 | update sys_role 35 | 36 | 37 | name = #{name}, 38 | 39 | 40 | description = #{description}, 41 | 42 | 43 | flag = #{flag}, 44 | 45 | 46 | where id = #{id} 47 | 48 | 49 | 50 | 51 | delete from sys_role where id = #{id} 52 | 53 | 54 | 55 | 56 | delete from sys_role where id in 57 | 58 | #{id} 59 | 60 | 61 | 62 | 63 | 66 | 67 | 68 | 71 | 72 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import com.example.common.Constants; 4 | import com.example.common.Result; 5 | import com.example.model.Role; 6 | import com.example.service.RoleService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.List; 12 | 13 | @RestController 14 | @RequestMapping("/role") 15 | public class RoleController { 16 | 17 | @Autowired 18 | private RoleService roleService; 19 | 20 | // 新增或者更新 21 | @PostMapping 22 | public Result save(@RequestBody Role role) { 23 | if(roleService.saveOrUpdate(role) != 0){ 24 | return Result.success(); 25 | }else { 26 | return Result.error(Constants.CODE_400,"参数都不能为空"); 27 | } 28 | } 29 | 30 | @DeleteMapping("/{id}") 31 | public Result delete(@PathVariable Integer id) { 32 | roleService.removeById(id); 33 | return Result.success(); 34 | } 35 | 36 | @PostMapping("/del/batch") 37 | public Result deleteBatch(@RequestBody List ids) { 38 | roleService.removeByIds(ids); 39 | return Result.success(); 40 | } 41 | 42 | @GetMapping 43 | public Result findAll() { 44 | return Result.success(roleService.findAll()); 45 | } 46 | // 47 | // @GetMapping("/{id}") 48 | // public Result findOne(@PathVariable Integer id) { 49 | // return Result.success(roleService.getById(id)); 50 | // } 51 | 52 | @GetMapping("/page") 53 | public Result findPage(@RequestParam String name, 54 | @RequestParam Integer pageNum, 55 | @RequestParam Integer pageSize) { 56 | return Result.success(roleService.findPage(name,pageNum,pageSize)); 57 | } 58 | 59 | /** 60 | * 绑定角色和菜单的关系 61 | * @param roleId 角色id 62 | * @param menuIds 菜单id数组 63 | * @return 64 | */ 65 | @RequestMapping ("/roleMenu/{roleId}") 66 | public Result roleMenu(@PathVariable Integer roleId, @RequestBody List menuIds) { 67 | roleService.setRoleMenu(roleId, menuIds); 68 | return Result.success(); 69 | } 70 | 71 | @GetMapping("/roleMenu/{roleId}") 72 | public Result getRoleMenu(@PathVariable Integer roleId) { 73 | return Result.success(roleService.getRoleMenu(roleId)); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/resources/mapper/MenuMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 14 | 15 | 16 | 17 | insert into sys_menu (name,path,icon,description,pid,page_path,sort_num) 18 | values (#{name},#{path},#{icon},#{description},#{pid},#{pagePath},#{sortNum}) 19 | 20 | 21 | 22 | 23 | update sys_menu 24 | 25 | 26 | name = #{name}, 27 | 28 | 29 | path = #{path}, 30 | 31 | 32 | icon = #{icon}, 33 | 34 | 35 | description = #{description}, 36 | 37 | 38 | pid = #{pid}, 39 | 40 | 41 | page_path = #{pagePath}, 42 | 43 | 44 | sort_num = #{sortNum}, 45 | 46 | 47 | where id = #{id} 48 | 49 | 50 | 51 | 52 | delete from sys_menu where id = #{id} 53 | 54 | 55 | 56 | 57 | delete from sys_menu where id in 58 | 59 | #{id} 60 | 61 | 62 | 63 | 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/example/config/interceptor/JwtInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.example.config.interceptor; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import com.auth0.jwt.JWT; 5 | import com.auth0.jwt.JWTVerifier; 6 | import com.auth0.jwt.algorithms.Algorithm; 7 | import com.auth0.jwt.exceptions.JWTDecodeException; 8 | import com.auth0.jwt.exceptions.JWTVerificationException; 9 | import com.example.common.Constants; 10 | import com.example.config.AuthAccess; 11 | import com.example.exception.ServiceException; 12 | import com.example.model.User; 13 | import com.example.service.UserService; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.web.method.HandlerMethod; 16 | import org.springframework.web.servlet.HandlerInterceptor; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | 21 | public class JwtInterceptor implements HandlerInterceptor { 22 | 23 | @Autowired 24 | private UserService userService; 25 | 26 | @Override 27 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { 28 | String token = request.getHeader("token"); 29 | 30 | // 如果不是映射到方法直接通过 31 | if(!(handler instanceof HandlerMethod)){ 32 | return true; 33 | } else { 34 | HandlerMethod h = (HandlerMethod) handler; 35 | AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class); 36 | if (authAccess != null) { 37 | return true; 38 | } 39 | } 40 | // 执行认证 41 | if (StrUtil.isBlank(token)) { 42 | throw new ServiceException(Constants.CODE_401, "无token,请重新登录"); 43 | } 44 | // 获取 token 中的 user id 45 | String userId; 46 | try { 47 | userId = JWT.decode(token).getAudience().get(0); 48 | } catch (JWTDecodeException j) { 49 | throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录"); 50 | } 51 | // 根据token中的userid查询数据库 52 | User user = userService.getById(userId); 53 | if (user == null) { 54 | throw new ServiceException(Constants.CODE_401, "用户不存在,请重新登录"); 55 | } 56 | // 用户密码加签验证 token 57 | JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); 58 | try { 59 | jwtVerifier.verify(token); // 验证token 60 | } catch (JWTVerificationException e) { 61 | throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录"); 62 | } 63 | return true; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/impl/CourseServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service.impl; 2 | 3 | import com.example.mapper.CourseMapper; 4 | import com.example.model.Course; 5 | import com.example.service.CourseService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | @Service 17 | public class CourseServiceImpl implements CourseService { 18 | 19 | @Resource 20 | private CourseMapper courseMapper; 21 | 22 | @Override 23 | public Map findPage(String name, Integer pageNum, Integer pageSize) { 24 | pageNum = (pageNum - 1) * pageSize; 25 | List data = courseMapper.findPage(name,pageNum, pageSize); 26 | Integer total = courseMapper.findTotal(name); 27 | Map courseMap = new HashMap<>(); 28 | courseMap.put("data", data); 29 | courseMap.put("total", total); 30 | return courseMap; 31 | } 32 | 33 | @Override 34 | public Integer removeById(Integer id) { 35 | return courseMapper.removeById(id); 36 | } 37 | 38 | @Override 39 | public Integer removeByIds(List id) { 40 | return courseMapper.removeByIds(id); 41 | } 42 | 43 | @Override 44 | public List findAll() { 45 | return null; 46 | } 47 | 48 | @Override 49 | public Integer saveOrUpdate(Course course) { 50 | if (course.getId() == null) { //user没有id,表示新增,否则更新 51 | if(null != course.getName() && !("".equals(course.getName()))){ 52 | return courseMapper.insert(course); 53 | }else{ 54 | return 0; 55 | } 56 | } else { 57 | if(null != course.getName() && !("".equals(course.getName()))){ 58 | return courseMapper.update(course); 59 | } 60 | return 0; 61 | } 62 | } 63 | 64 | @Override 65 | public String getTeacherById(Integer id) { 66 | return courseMapper.getTeacherById(id); 67 | } 68 | 69 | @Transactional 70 | @Override 71 | public int setStudentCourse(Integer courseId, Integer studentId) { 72 | courseMapper.deleteStudentCourse(courseId,studentId); 73 | return courseMapper.setStudentCourse(courseId,studentId); 74 | } 75 | 76 | @Override 77 | public Integer update(Course course) { 78 | return courseMapper.update(course); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/MenuController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import com.example.common.Constants; 4 | import com.example.common.Result; 5 | import com.example.mapper.DictMapper; 6 | import com.example.model.Menu; 7 | import com.example.service.MenuService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import javax.annotation.Resource; 12 | import java.util.List; 13 | import java.util.stream.Collectors; 14 | 15 | @RestController 16 | @RequestMapping("/menu") 17 | public class MenuController { 18 | 19 | @Autowired 20 | private MenuService menuService; 21 | 22 | @Resource 23 | private DictMapper dictMapper; 24 | // @Resource 25 | // private IMenuService menuService; 26 | // 27 | // @Resource 28 | // private DictMapper dictMapper; 29 | // 30 | // // 新增或者更新 31 | @PostMapping 32 | public Result save(@RequestBody Menu menu) { 33 | if(menuService.saveOrUpdate(menu) != 0){ 34 | return Result.success(); 35 | } 36 | return Result.error(Constants.CODE_400,"名称不能为空"); 37 | } 38 | 39 | @DeleteMapping("/{id}") 40 | public Result delete(@PathVariable Integer id) { 41 | menuService.removeById(id); 42 | return Result.success(); 43 | } 44 | 45 | @PostMapping("/del/batch") 46 | public Result deleteBatch(@RequestBody List ids) { 47 | menuService.removeByIds(ids); 48 | return Result.success(); 49 | } 50 | 51 | // @GetMapping("/ids") 52 | // public Result findAllIds() { 53 | // return Result.success(menuService.list().stream().map(Menu::getId)); 54 | // } 55 | 56 | @GetMapping 57 | public Result findAll(@RequestParam(defaultValue = "") String name) { 58 | return Result.success(menuService.findAll(name)); 59 | } 60 | // 61 | // @GetMapping("/{id}") 62 | // public Result findOne(@PathVariable Integer id) { 63 | // return Result.success(menuService.getById(id)); 64 | // } 65 | // 66 | // @GetMapping("/page") 67 | // public Result findPage(@RequestParam String name, 68 | // @RequestParam Integer pageNum, 69 | // @RequestParam Integer pageSize) { 70 | // QueryWrapper queryWrapper = new QueryWrapper<>(); 71 | // queryWrapper.like("name", name); 72 | // queryWrapper.orderByDesc("id"); 73 | // return Result.success(menuService.page(new Page<>(pageNum, pageSize), queryWrapper)); 74 | // } 75 | 76 | @GetMapping("/icons") 77 | public Result getIcons() { 78 | return Result.success(dictMapper.findAll()); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/resources/mapper/CourseMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 16 | 17 | 18 | 26 | 27 | 28 | 29 | delete from course where id = #{id} 30 | 31 | 32 | 33 | 34 | delete from course where id in 35 | 36 | #{id} 37 | 38 | 39 | 40 | 41 | 44 | 45 | 46 | 47 | insert into course (name,score,times,state,teacher_id) 48 | values (#{name},#{score},#{times},#{state},#{teacherId}) 49 | 50 | 51 | 52 | 53 | update course 54 | 55 | 56 | name = #{name}, 57 | 58 | 59 | score = #{score}, 60 | 61 | 62 | times = #{times}, 63 | 64 | 65 | state = #{state}, 66 | 67 | 68 | teacher_id = #{teacherId}, 69 | 70 | 71 | where id = #{id} 72 | 73 | 74 | 75 | 78 | 79 | 80 | delete from student_course where student_id = #{studentId} and course_id = #{courseId} 81 | 82 | 83 | 84 | insert into student_course(student_id,course_id) values (#{studentId},#{courseId}) 85 | 86 | 87 | -------------------------------------------------------------------------------- /src/main/resources/mapper/FilesMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | insert into sys_file (name,type,size,url,md5) values (#{name},#{type},#{size},#{url},#{md5}) 7 | 8 | 9 | 12 | 13 | 14 | 25 | 26 | 27 | 35 | 36 | 37 | 40 | 41 | 42 | 48 | 49 | 50 | 51 | delete from sys_file where id = #{id} 52 | 53 | 54 | 55 | DELETE FROM sys_file WHERE id IN 56 | 57 | #{id} 58 | 59 | 60 | 61 | 62 | 63 | update sys_file 64 | 65 | 66 | name = #{name}, 67 | 68 | 69 | type = #{type}, 70 | 71 | 72 | size = #{size}, 73 | 74 | 75 | url = #{url}, 76 | 77 | 78 | is_delete = #{isDelete}, 79 | 80 | 81 | enable = #{enable}, 82 | 83 | 84 | md5 = #{md5}, 85 | 86 | 87 | where id = #{id} 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/EchartsController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import cn.hutool.core.collection.CollUtil; 4 | import cn.hutool.core.date.DateUtil; 5 | import cn.hutool.core.date.Quarter; 6 | import com.example.common.Result; 7 | import com.example.mapper.FilesMapper; 8 | import com.example.model.User; 9 | import com.example.service.UserService; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.data.redis.core.RedisTemplate; 12 | import org.springframework.data.redis.core.StringRedisTemplate; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import javax.annotation.Resource; 18 | import java.util.Date; 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | @RestController 24 | @RequestMapping("/echarts") 25 | public class EchartsController { 26 | 27 | @Autowired 28 | private UserService userService; 29 | 30 | @Resource 31 | private FilesMapper filesMapper; 32 | 33 | @Autowired 34 | private StringRedisTemplate stringRedisTemplate; 35 | 36 | // @Autowired 37 | // private StringRedisTemplate stringRedisTemplate; 38 | 39 | @GetMapping("/example") 40 | public Result get() { 41 | Map map = new HashMap<>(); 42 | map.put("x", CollUtil.newArrayList("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")); 43 | map.put("y", CollUtil.newArrayList(150, 230, 224, 218, 135, 147, 260)); 44 | return Result.success(map); 45 | } 46 | 47 | @GetMapping("/members") 48 | public Result members() { 49 | List list = userService.selectAll(); 50 | int q1 = 0; // 第一季度 51 | int q2 = 0; // 第二季度 52 | int q3 = 0; // 第三季度 53 | int q4 = 0; // 第四季度 54 | for (User user : list) { 55 | Date createTime = user.getCreateTime(); 56 | Quarter quarter = DateUtil.quarterEnum(createTime); 57 | switch (quarter) { 58 | case Q1: q1 += 1; break; 59 | case Q2: q2 += 1; break; 60 | case Q3: q3 += 1; break; 61 | case Q4: q4 += 1; break; 62 | default: break; 63 | } 64 | } 65 | return Result.success(CollUtil.newArrayList(q1, q2, q3, q4)); 66 | } 67 | 68 | // @AuthAccess 69 | // @GetMapping("/file/front/all") 70 | //// @Cacheable(value = "files" ,key = "'frontAll'") 71 | // public Result frontAll() { 72 | // // 1. 从缓存获取数据 73 | // String jsonStr = stringRedisTemplate.opsForValue().get(Constants.FILES_KEY); 74 | // List files; 75 | // if (StrUtil.isBlank(jsonStr)) { // 2. 取出来的json是空的 76 | // files = fileMapper.selectList(null); // 3. 从数据库取出数据 77 | // // 4. 再去缓存到redis 78 | // stringRedisTemplate.opsForValue().set(Constants.FILES_KEY, JSONUtil.toJsonStr(files)); 79 | // } else { 80 | // // 减轻数据库的压力 81 | // // 5. 如果有, 从redis缓存中获取数据 82 | // files = JSONUtil.toBean(jsonStr, new TypeReference>() { 83 | // }, true); 84 | // } 85 | // return Result.success(files); 86 | // } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.6.8 9 | 10 | 11 | com.example 12 | springboot_firstPractice 13 | 0.0.1-SNAPSHOT 14 | springboot_firstPractice 15 | springboot_firstPractice 16 | 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-web 23 | 24 | 25 | org.mybatis.spring.boot 26 | mybatis-spring-boot-starter 27 | 2.2.2 28 | 29 | 30 | 31 | mysql 32 | mysql-connector-java 33 | runtime 34 | 35 | 36 | org.projectlombok 37 | lombok 38 | true 39 | 40 | 41 | 42 | com.baomidou 43 | mybatis-plus-boot-starter 44 | 3.5.1 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | cn.hutool 53 | hutool-all 54 | 5.7.20 55 | 56 | 57 | org.apache.poi 58 | poi-ooxml 59 | 4.1.2 60 | 61 | 62 | 63 | com.auth0 64 | java-jwt 65 | 3.10.3 66 | 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-data-redis 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-maven-plugin 79 | 80 | 81 | 82 | org.projectlombok 83 | lombok 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service.impl; 2 | 3 | import cn.hutool.core.collection.CollUtil; 4 | import com.example.mapper.MenuMapper; 5 | import com.example.mapper.RoleMapper; 6 | import com.example.mapper.RoleMenuMapper; 7 | import com.example.model.Menu; 8 | import com.example.model.Role; 9 | import com.example.model.RoleMenu; 10 | import com.example.model.User; 11 | import com.example.service.MenuService; 12 | import com.example.service.RoleService; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | 17 | import javax.annotation.Resource; 18 | import java.util.HashMap; 19 | import java.util.List; 20 | import java.util.Map; 21 | @Service 22 | public class RoleServiceImpl implements RoleService { 23 | 24 | @Resource 25 | private RoleMapper roleMapper; 26 | 27 | @Resource 28 | private RoleMenuMapper roleMenuMapper; 29 | 30 | @Resource 31 | private MenuMapper menuMapper; 32 | 33 | @Transactional 34 | @Override 35 | public void setRoleMenu(Integer roleId, List menuIds) { 36 | //先删除当前角色id所有的绑定关系 37 | roleMenuMapper.deleteByRoleId(roleId); 38 | //再把前端传过来的菜单id数组绑定到当前的角色id上去 39 | List menuIdsCopy = CollUtil.newArrayList(menuIds); 40 | for(Integer menuId : menuIds){ 41 | Menu menu = menuMapper.getById(menuId); 42 | //是二级菜单并且传过来的menuId数组里面没有他的父级Id 43 | if(menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())){ 44 | //补上这个父级Id 45 | RoleMenu roleMenu = new RoleMenu(); 46 | roleMenu.setRoleId(roleId); 47 | roleMenu.setMenuId(menu.getPid()); 48 | roleMenuMapper.insert(roleMenu); 49 | menuIdsCopy.add(menu.getPid()); 50 | } 51 | RoleMenu roleMenu = new RoleMenu(); 52 | roleMenu.setRoleId(roleId); 53 | roleMenu.setMenuId(menuId); 54 | roleMenuMapper.insert(roleMenu); 55 | } 56 | } 57 | 58 | @Override 59 | public List getRoleMenu(Integer roleId) { 60 | return roleMenuMapper.getByRoleId(roleId); 61 | } 62 | 63 | @Override 64 | public Map findPage(String name, Integer pageNum, Integer pageSize) { 65 | pageNum = (pageNum - 1) * pageSize; 66 | List data = roleMapper.findPage(name,pageNum, pageSize); 67 | Integer total = roleMapper.findTotal(name); 68 | Map roleMap = new HashMap<>(); 69 | roleMap.put("data", data); 70 | roleMap.put("total", total); 71 | return roleMap; 72 | } 73 | 74 | @Override 75 | public Integer saveOrUpdate(Role role) { 76 | if (role.getId() == null) { //role没有id,表示新增,否则更新 77 | //名字,描述,唯一标识都不为空或空串 78 | if(null != role.getName() && !("".equals(role.getName())) 79 | && null != role.getDescription() && !("".equals(role.getDescription())) 80 | && null != role.getFlag() && !("".equals(role.getFlag()))){ 81 | return roleMapper.insert(role); 82 | }else{ 83 | return 0; 84 | } 85 | } else { 86 | if(null != role.getName() && !("".equals(role.getName())) 87 | && null != role.getDescription() && !("".equals(role.getDescription())) 88 | && null != role.getFlag() && !("".equals(role.getFlag()))){ 89 | return roleMapper.update(role); 90 | }else{ 91 | return 0; 92 | } 93 | } 94 | } 95 | 96 | @Override 97 | public int removeById(Integer id) { 98 | return roleMapper.removeById(id); 99 | } 100 | 101 | @Override 102 | public int removeByIds(List ids) { 103 | return roleMapper.removeByIds(ids); 104 | } 105 | 106 | @Override 107 | public List findAll() { 108 | return roleMapper.findAll(); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/FilesController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import cn.hutool.core.io.FileUtil; 4 | import cn.hutool.core.util.IdUtil; 5 | import cn.hutool.core.util.StrUtil; 6 | import cn.hutool.crypto.SecureUtil; 7 | import cn.hutool.db.Page; 8 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; 9 | import com.example.common.Result; 10 | import com.example.mapper.FilesMapper; 11 | import com.example.mapper.UserMapper; 12 | import com.example.model.Files; 13 | import com.example.model.User; 14 | import com.example.utils.TokenUtil; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.beans.factory.annotation.Value; 17 | import org.springframework.web.bind.annotation.*; 18 | import org.springframework.web.multipart.MultipartFile; 19 | 20 | import javax.annotation.Resource; 21 | import javax.servlet.ServletOutputStream; 22 | import javax.servlet.http.HttpServletResponse; 23 | import java.io.File; 24 | import java.io.IOException; 25 | import java.net.URLEncoder; 26 | import java.util.HashMap; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | /** 31 | * 文件上传相关接口 32 | */ 33 | @RestController 34 | @RequestMapping("/file") 35 | public class FilesController { 36 | 37 | @Value("${files.upload.path}") 38 | private String fileUploadPath; 39 | 40 | @Resource 41 | private FilesMapper filesMapper; 42 | 43 | /** 44 | * 文件上传接口 45 | * @param file 前端传递的文件 46 | * @return 47 | * @throws IOException 48 | */ 49 | @PostMapping("/upload") 50 | public String upload(@RequestParam MultipartFile file) throws IOException { 51 | String originalFilename = file.getOriginalFilename(); 52 | String type = FileUtil.extName(originalFilename); 53 | long size = file.getSize(); 54 | 55 | // 定义一个文件唯一的标识码 56 | String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type; 57 | 58 | File uploadFile = new File(fileUploadPath + fileUUID); 59 | // 判断配置的文件目录是否存在,若不存在则创建一个新的文件目录 60 | File parentFile = uploadFile.getParentFile(); 61 | if(!parentFile.exists()) { 62 | parentFile.mkdirs(); 63 | } 64 | 65 | String url; 66 | // 获取文件的md5 67 | String md5 = SecureUtil.md5(file.getInputStream()); 68 | // 从数据库查询是否存在相同的记录 69 | Files dbFiles = filesMapper.getByMd5(md5); 70 | if (dbFiles != null) { 71 | url = dbFiles.getUrl(); 72 | } else { 73 | // 上传文件到磁盘 74 | file.transferTo(uploadFile); 75 | // 数据库若不存在重复文件,则不删除刚才上传的文件 76 | url = "http://localhost:8081/file/" + fileUUID; 77 | } 78 | 79 | // 存储数据库 80 | Files saveFile = new Files(); 81 | saveFile.setName(originalFilename); 82 | saveFile.setType(type); 83 | saveFile.setSize(size/1024); // 单位 kb 84 | saveFile.setUrl(url); 85 | saveFile.setMd5(md5); 86 | filesMapper.insert(saveFile); 87 | return url; 88 | } 89 | @GetMapping("/{fileUUID}") 90 | public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException { 91 | // 根据文件的唯一标识码获取文件 92 | File uploadFile = new File(fileUploadPath + fileUUID); 93 | // 设置输出流的格式 94 | ServletOutputStream os = response.getOutputStream(); 95 | response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8")); 96 | response.setContentType("application/octet-stream"); 97 | 98 | // 读取文件的字节流 99 | os.write(FileUtil.readBytes(uploadFile)); 100 | os.flush(); 101 | os.close(); 102 | } 103 | 104 | /** 105 | * 分页查询接口 106 | * @param pageNum 107 | * @param pageSize 108 | * @param name 109 | * @return 110 | */ 111 | @GetMapping("/page") 112 | public Result findPage(@RequestParam Integer pageNum, 113 | @RequestParam Integer pageSize, 114 | @RequestParam(defaultValue = "") String name) { 115 | pageNum = (pageNum - 1) * pageSize; 116 | List data = filesMapper.selectPage(pageNum, pageSize, name); 117 | Integer total = filesMapper.selectTotal(name); 118 | Map filesMap = new HashMap<>(); 119 | filesMap.put("data", data); 120 | filesMap.put("total", total); 121 | return Result.success(filesMap); 122 | } 123 | @DeleteMapping("/{id}") 124 | public Result delete(@PathVariable Integer id) { 125 | Files files = filesMapper.selectById(id); 126 | files.setIsDelete(true); 127 | filesMapper.updateById(files); 128 | return Result.success(); 129 | } 130 | 131 | @PostMapping("/del/batch") 132 | public Result deleteBatch(@RequestBody List ids) { 133 | List filesList = filesMapper.selectByIds(ids); 134 | for (Files file : filesList) { 135 | file.setIsDelete(true); 136 | filesMapper.updateById(file); 137 | } 138 | return Result.success(); 139 | } 140 | @PostMapping("/update") 141 | public Result updateById(@RequestBody Files files) { 142 | filesMapper.updateById(files); 143 | return Result.success(); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import cn.hutool.crypto.SecureUtil; 5 | import cn.hutool.poi.excel.ExcelReader; 6 | import cn.hutool.poi.excel.ExcelUtil; 7 | import cn.hutool.poi.excel.ExcelWriter; 8 | import com.example.common.Constants; 9 | import com.example.common.Result; 10 | import com.example.controller.dto.UserDTO; 11 | import com.example.controller.dto.UserPasswordDTO; 12 | import com.example.exception.ServiceException; 13 | import com.example.model.User; 14 | import com.example.service.impl.UserServiceImpl; 15 | import com.example.utils.TokenUtil; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.web.bind.annotation.*; 18 | import org.springframework.web.multipart.MultipartFile; 19 | 20 | import javax.servlet.ServletOutputStream; 21 | import javax.servlet.http.HttpServletResponse; 22 | import java.io.InputStream; 23 | import java.net.URLEncoder; 24 | import java.util.List; 25 | import java.util.Map; 26 | 27 | @RestController 28 | @RequestMapping("/user") 29 | public class UserController { 30 | 31 | @Autowired 32 | private UserServiceImpl userService; 33 | 34 | @GetMapping("/selectAll") 35 | public List selectAll(){ 36 | //查询全部 37 | return userService.selectAll(); 38 | } 39 | 40 | @PostMapping("/save") 41 | public Result save(@RequestBody User user){ 42 | //新增或更新 43 | if(userService.save(user) != 0){ 44 | return Result.success(); 45 | }else { 46 | return Result.error(Constants.CODE_400,"名字不能为空"); 47 | } 48 | } 49 | @DeleteMapping("/{id}") 50 | public Result deleteById(@PathVariable Integer id){ 51 | //删除 52 | return Result.success(userService.deleteById(id)); 53 | } 54 | //@RequestParam 接收?page=2&pageSize=10 55 | @GetMapping("/page") 56 | public Map selectPage(@RequestParam Integer pageNum, 57 | @RequestParam Integer pageSize, 58 | @RequestParam String username, 59 | @RequestParam String email, 60 | @RequestParam String address){ 61 | //动态条件查询全部 62 | return userService.selectPage(pageNum,pageSize,username,email,address); 63 | } 64 | 65 | @PostMapping("/del/batch") 66 | public Result deleteBatch(@RequestBody List id){ 67 | return Result.success(userService.deleteBatch(id)); 68 | } 69 | 70 | /** 71 | * 导出接口 72 | */ 73 | @GetMapping("/export") 74 | public void export(HttpServletResponse response) throws Exception{ 75 | //从数据库查询出所有的用户 76 | List list = userService.selectAll(); 77 | //在内存操作,写出到浏览器 78 | ExcelWriter writer = ExcelUtil.getWriter(true); 79 | 80 | //一次性写出list内的对象到excel,使用默认样式,强制输出标题 81 | writer.write(list,true); 82 | //设置浏览器响应的格式 83 | response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); 84 | String fileName = URLEncoder.encode("用户信息","Utf-8"); 85 | response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx"); 86 | 87 | ServletOutputStream out = response.getOutputStream(); 88 | writer.flush(out,true); 89 | out.close(); 90 | writer.close(); 91 | } 92 | 93 | /** 94 | * excel 导入 95 | * @param file 96 | * @throws Exception 97 | */ 98 | @PostMapping("/import") 99 | public void imp(MultipartFile file) throws Exception{ 100 | InputStream inputStream = file.getInputStream(); 101 | ExcelReader reader = ExcelUtil.getReader(inputStream); 102 | List list = reader.readAll(User.class); 103 | userService.insertBatch(list); 104 | } 105 | 106 | @PostMapping("/login") 107 | public Result login(@RequestBody UserDTO userDTO){ 108 | String username = userDTO.getUsername(); 109 | String password = userDTO.getPassword(); 110 | if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){ 111 | return Result.error(Constants.CODE_400,"参数错误"); 112 | } 113 | UserDTO userDTOResult = userService.login(userDTO); 114 | return Result.success(userDTOResult); 115 | } 116 | 117 | @PostMapping("/register") 118 | public Result register(@RequestBody UserDTO userDTO) { 119 | String username = userDTO.getUsername(); 120 | String password = userDTO.getPassword(); 121 | if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){ 122 | return Result.error(Constants.CODE_400,"参数错误"); 123 | } 124 | return Result.success(userService.register(userDTO)); 125 | } 126 | @GetMapping("/username/{username}") 127 | public Result getPerson(@PathVariable String username){ 128 | return Result.success(userService.getPerson(username)); 129 | } 130 | 131 | @PostMapping("/password") 132 | public Result password(@RequestBody UserPasswordDTO userPasswordDTO) { 133 | // userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword())); 134 | // userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword())); 135 | userService.updatePassword(userPasswordDTO); 136 | return Result.success(); 137 | } 138 | @GetMapping("/role/{role}") 139 | public Result findUsersByRole(@PathVariable String role) { 140 | List userList = userService.selectByRole(role); 141 | return Result.success(userList); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 30 | 31 | 32 | 33 | insert into sys_user (username,password,nickname,email,phone,address,role) values (#{username},#{password},#{nickname},#{email},#{phone},#{address},#{role}) 34 | 35 | 36 | 37 | 38 | update sys_user 39 | 40 | 41 | username = #{username}, 42 | 43 | 44 | password = #{password}, 45 | 46 | 47 | nickname = #{nickname}, 48 | 49 | 50 | email = #{email}, 51 | 52 | 53 | phone = #{phone}, 54 | 55 | 56 | address = #{address}, 57 | 58 | 59 | role = #{role}, 60 | 61 | 62 | where id = #{id} 63 | 64 | 65 | 66 | delete from sys_user where id = #{id} 67 | 68 | 69 | 70 | 93 | 94 | 95 | 109 | 110 | 111 | 112 | DELETE FROM sys_user WHERE id IN 113 | 114 | #{id} 115 | 116 | 117 | 118 | 119 | 120 | INSERT INTO sys_user (username, password, nickname, email, phone,address,avatar_url) VALUES 121 | 122 | (#{item.username},#{item.password},#{item.nickname},#{item.email},#{item.phone},#{item.address},#{item.avatarUrl}) 123 | 124 | 125 | 126 | 127 | 130 | 131 | 132 | 135 | 136 | 137 | 142 | 143 | 148 | 149 | 150 | 151 | update sys_user set password = #{newPassword} where username = #{username} and password = #{password} 152 | 153 | 154 | 155 | 158 | 159 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.service.impl; 2 | 3 | import cn.hutool.core.lang.TypeReference; 4 | import cn.hutool.core.util.StrUtil; 5 | import cn.hutool.json.JSONUtil; 6 | import com.example.common.Constants; 7 | import com.example.controller.dto.UserDTO; 8 | import com.example.controller.dto.UserPasswordDTO; 9 | import com.example.exception.ServiceException; 10 | import com.example.mapper.MenuMapper; 11 | import com.example.mapper.RoleMapper; 12 | import com.example.mapper.RoleMenuMapper; 13 | import com.example.mapper.UserMapper; 14 | import com.example.model.Menu; 15 | import com.example.model.User; 16 | import com.example.service.UserService; 17 | import com.example.utils.TokenUtil; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.data.redis.core.StringRedisTemplate; 20 | import org.springframework.data.redis.core.ValueOperations; 21 | import org.springframework.stereotype.Service; 22 | 23 | import javax.annotation.Resource; 24 | import java.util.ArrayList; 25 | import java.util.HashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.stream.Collectors; 29 | 30 | @Service 31 | public class UserServiceImpl implements UserService { 32 | 33 | @Resource 34 | private UserMapper userMapper; 35 | 36 | @Resource 37 | private RoleMapper roleMapper; 38 | 39 | @Resource 40 | private RoleMenuMapper roleMenuMapper; 41 | 42 | @Resource 43 | private MenuMapper menuMapper; 44 | 45 | @Resource 46 | private StringRedisTemplate stringRedisTemplate; 47 | 48 | @Override 49 | public List selectAll() { 50 | return userMapper.selectAll(); 51 | } 52 | 53 | @Override 54 | public int save(User user) { 55 | if (user.getId() == null) { //user没有id,表示新增,否则更新 56 | if(null != user.getUsername() && !("".equals(user.getUsername()))){ 57 | flushRedis(); 58 | return userMapper.insert(user); 59 | }else{ 60 | return 0; 61 | } 62 | } else { 63 | if(null != user.getUsername() && !("".equals(user.getUsername()))){ 64 | flushRedis(); 65 | return userMapper.update(user); 66 | } 67 | return 0; 68 | } 69 | } 70 | 71 | @Override 72 | public int deleteById(Integer id) { 73 | flushRedis(); 74 | return userMapper.deleteById(id); 75 | } 76 | 77 | @Override 78 | public Map selectPage(Integer pageNum, Integer pageSize, String username, String email, String address) { 79 | pageNum = (pageNum - 1) * pageSize; 80 | //String jsonStr = stringRedisTemplate.opsForValue().get(Constants.USER_ALL); 81 | Map userMap = new HashMap<>(); 82 | //redis中没有数据,查询数据库,并保存到redis 83 | //if(StrUtil.isBlank(jsonStr)){ 84 | List data = userMapper.selectPage(pageNum, pageSize, username, email, address); 85 | Integer total = userMapper.selectTotal(username, email, address); 86 | userMap = new HashMap<>(); 87 | userMap.put("data", data); 88 | userMap.put("total", total); 89 | //stringRedisTemplate.opsForValue().set(Constants.USER_ALL, JSONUtil.toJsonStr(userMap)); 90 | return userMap; 91 | //}else{ 92 | //redis中有数据,直接获取 93 | //userMap = JSONUtil.toBean(jsonStr, new TypeReference>() { 94 | //},true); 95 | //return userMap; 96 | //} 97 | } 98 | 99 | @Override 100 | public int selectTotal(String username, String email, String address) { 101 | return userMapper.selectTotal(username, email, address); 102 | } 103 | 104 | @Override 105 | public int deleteBatch(List id) { 106 | flushRedis(); 107 | return userMapper.deleteBatch(id); 108 | } 109 | 110 | @Override 111 | public int insertBatch(List userList) { 112 | return userMapper.insertBatch(userList); 113 | } 114 | 115 | public UserDTO login(UserDTO userDTO) { 116 | UserDTO userDTOResult; 117 | try{ 118 | userDTOResult = userMapper.login(userDTO); 119 | }catch (Exception e){ 120 | throw new ServiceException(Constants.CODE_500,"系统错误"); 121 | } 122 | if(userDTOResult != null){ 123 | //设置token 124 | String token = TokenUtil.genToken(userDTOResult.getId(), userDTOResult.getPassword()); 125 | userDTOResult.setToken(token); 126 | String role = userDTOResult.getRole(); 127 | Integer roleId = roleMapper.getByFlag(role); 128 | List menuIds = roleMenuMapper.getByRoleId(roleId); 129 | 130 | //查出所有用户的菜单 131 | List list = menuMapper.findAll(""); 132 | // 找出pid为null的一级菜单 133 | List menus = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList()); 134 | // 找出一级菜单的子菜单 135 | for (Menu menu : menus) { 136 | // 筛选所有数据中pid=父级id的数据就是二级菜单 137 | menu.setChildren(list.stream().filter(m -> menu.getId().equals(m.getPid())).collect(Collectors.toList())); 138 | } 139 | 140 | List roleMenus = new ArrayList<>(); 141 | //筛选当前用户的菜单 142 | for (Menu menu : menus) { 143 | if(menuIds.contains(menu.getId())){ 144 | roleMenus.add(menu); 145 | } 146 | List children = menu.getChildren(); 147 | //移除children里面不在menuIds集合中的元素 148 | children.removeIf(child -> !menuIds.contains(child.getId())); 149 | } 150 | userDTOResult.setMenus(roleMenus); 151 | return userDTOResult; 152 | }else{ 153 | throw new ServiceException(Constants.CODE_600,"用户名或密码错误"); 154 | } 155 | } 156 | 157 | public UserDTO register(UserDTO userDTO) { 158 | UserDTO userDTOResult = userMapper.register(userDTO); 159 | if(userDTOResult == null){ 160 | User user = new User(); 161 | user.setUsername(userDTO.getUsername()); 162 | user.setPassword(userDTO.getPassword()); 163 | user.setNickname(userDTO.getNickname()); 164 | userMapper.insert(user); 165 | }else{ 166 | throw new ServiceException(Constants.CODE_600,"用户已存在"); 167 | } 168 | return userDTOResult; 169 | } 170 | 171 | @Override 172 | public User getPerson(String username) { 173 | return userMapper.getPerson(username); 174 | } 175 | 176 | @Override 177 | public User getById(String id) { 178 | return userMapper.getById(id); 179 | } 180 | 181 | @Override 182 | public void updatePassword(UserPasswordDTO userPasswordDTO) { 183 | int update = userMapper.updatePassword(userPasswordDTO); 184 | if (update < 1) { 185 | throw new ServiceException(Constants.CODE_600, "密码错误"); 186 | } 187 | } 188 | 189 | @Override 190 | public List selectByRole(String role) { 191 | return userMapper.selectByRole(role); 192 | } 193 | 194 | private void flushRedis(){ 195 | stringRedisTemplate.delete(Constants.USER_ALL); 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /sql.sql: -------------------------------------------------------------------------------- 1 | SET NAMES utf8mb4; 2 | 3 | -- ---------------------------- 4 | -- Table structure for course 5 | -- ---------------------------- 6 | DROP TABLE IF EXISTS `course`; 7 | CREATE TABLE `course` ( 8 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', 9 | `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '课程名称', 10 | `score` int(11) NULL DEFAULT NULL COMMENT '学分', 11 | `times` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '上课时间', 12 | `state` tinyint(1) NULL DEFAULT NULL COMMENT '是否开课', 13 | `teacher_id` int(11) NULL DEFAULT NULL COMMENT '授课老师id', 14 | PRIMARY KEY (`id`) USING BTREE 15 | ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 16 | 17 | -- ---------------------------- 18 | -- Records of course 19 | -- ---------------------------- 20 | INSERT INTO `course` VALUES (1, '大学物理', 10, '40', 0,null); 21 | INSERT INTO `course` VALUES (2, '高等数学', 10, '45', NULL,null); 22 | INSERT INTO `course` VALUES (3, '大学英语', 10, '30', NULL,null); 23 | 24 | -- ---------------------------- 25 | -- Table structure for student_course 26 | -- ---------------------------- 27 | DROP TABLE IF EXISTS `student_course`; 28 | CREATE TABLE `student_course` ( 29 | `student_id` int(11) NOT NULL, 30 | `course_id` int(11) NOT NULL, 31 | PRIMARY KEY (`student_id`, `course_id`) USING BTREE 32 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 33 | 34 | 35 | 36 | -- ---------------------------- 37 | -- Table structure for sys_dict 38 | -- ---------------------------- 39 | DROP TABLE IF EXISTS `sys_dict`; 40 | CREATE TABLE `sys_dict` ( 41 | `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '名称', 42 | `value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '内容', 43 | `type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '类型' 44 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 45 | 46 | -- ---------------------------- 47 | -- Records of sys_dict 48 | -- ---------------------------- 49 | INSERT INTO `sys_dict` VALUES ('user', 'el-icon-user', 'icon'); 50 | INSERT INTO `sys_dict` VALUES ('house', 'el-icon-house', 'icon'); 51 | INSERT INTO `sys_dict` VALUES ('menu', 'el-icon-menu', 'icon'); 52 | INSERT INTO `sys_dict` VALUES ('s-custom', 'el-icon-s-custom', 'icon'); 53 | INSERT INTO `sys_dict` VALUES ('s-grid', 'el-icon-s-grid', 'icon'); 54 | INSERT INTO `sys_dict` VALUES ('document', 'el-icon-document', 'icon'); 55 | INSERT INTO `sys_dict` VALUES ('s-marketing', 'el-icon-s-marketing', 'icon'); 56 | 57 | 58 | -- ---------------------------- 59 | -- Table structure for sys_menu 60 | -- ---------------------------- 61 | DROP TABLE IF EXISTS `sys_menu`; 62 | CREATE TABLE `sys_menu` ( 63 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', 64 | `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '名称', 65 | `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '路径', 66 | `icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '图标', 67 | `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '描述', 68 | `pid` int(11) NULL DEFAULT NULL COMMENT '父级id', 69 | `page_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '页面路径', 70 | `sort_num` int(11) NULL DEFAULT NULL COMMENT '排序', 71 | PRIMARY KEY (`id`) USING BTREE 72 | ) ENGINE = InnoDB AUTO_INCREMENT = 44 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 73 | 74 | -- ---------------------------- 75 | -- Records of sys_menu 76 | -- ---------------------------- 77 | INSERT INTO `sys_menu` VALUES (2, '数据报表', '/dashbord', 'el-icon-s-marketing', '11', NULL, 'Dashbord', 100); 78 | INSERT INTO `sys_menu` VALUES (4, '系统管理', NULL, 'el-icon-s-grid', NULL, NULL, NULL, 300); 79 | INSERT INTO `sys_menu` VALUES (5, '用户管理', '/user', 'el-icon-user', NULL, 4, 'User', 301); 80 | INSERT INTO `sys_menu` VALUES (6, '角色管理', '/role', 'el-icon-s-custom', NULL, 4, 'Role', 302); 81 | INSERT INTO `sys_menu` VALUES (7, '菜单管理', '/menu', 'el-icon-menu', NULL, 4, 'Menu', 303); 82 | INSERT INTO `sys_menu` VALUES (39, '课程管理', '/course', 'el-icon-menu', NULL, NULL, 'Course', 201); 83 | 84 | 85 | -- ---------------------------- 86 | -- Table structure for sys_role 87 | -- ---------------------------- 88 | DROP TABLE IF EXISTS `sys_role`; 89 | CREATE TABLE `sys_role` ( 90 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', 91 | `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '名称', 92 | `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '描述', 93 | `flag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '唯一标识', 94 | PRIMARY KEY (`id`) USING BTREE 95 | ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 96 | 97 | -- ---------------------------- 98 | -- Records of sys_role 99 | -- ---------------------------- 100 | INSERT INTO `sys_role` VALUES (1, '管理员', '管理员', 'ROLE_ADMIN'); 101 | INSERT INTO `sys_role` VALUES (2, '学生', '学生', 'ROLE_STUDENT'); 102 | INSERT INTO `sys_role` VALUES (3, '老师', '老师', 'ROLE_TEACHER'); 103 | 104 | -- ---------------------------- 105 | -- Table structure for sys_role_menu 106 | -- ---------------------------- 107 | DROP TABLE IF EXISTS `sys_role_menu`; 108 | CREATE TABLE `sys_role_menu` ( 109 | `role_id` int(11) NOT NULL COMMENT '角色id', 110 | `menu_id` int(11) NOT NULL COMMENT '菜单id', 111 | PRIMARY KEY (`role_id`, `menu_id`) USING BTREE 112 | ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '角色菜单关系表' ROW_FORMAT = Dynamic; 113 | 114 | -- ---------------------------- 115 | -- Records of sys_role_menu 116 | -- ---------------------------- 117 | INSERT INTO `sys_role_menu` VALUES (1, 2); 118 | INSERT INTO `sys_role_menu` VALUES (1, 4); 119 | INSERT INTO `sys_role_menu` VALUES (1, 5); 120 | INSERT INTO `sys_role_menu` VALUES (1, 6); 121 | INSERT INTO `sys_role_menu` VALUES (1, 7); 122 | INSERT INTO `sys_role_menu` VALUES (1, 8); 123 | INSERT INTO `sys_role_menu` VALUES (1, 9); 124 | INSERT INTO `sys_role_menu` VALUES (1, 10); 125 | INSERT INTO `sys_role_menu` VALUES (1, 39); 126 | INSERT INTO `sys_role_menu` VALUES (1, 40); 127 | INSERT INTO `sys_role_menu` VALUES (1, 41); 128 | INSERT INTO `sys_role_menu` VALUES (1, 42); 129 | INSERT INTO `sys_role_menu` VALUES (1, 43); 130 | 131 | 132 | -- ---------------------------- 133 | -- Table structure for sys_user 134 | -- ---------------------------- 135 | DROP TABLE IF EXISTS `sys_user`; 136 | CREATE TABLE `sys_user` ( 137 | `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', 138 | `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户名', 139 | `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT 123 COMMENT '密码', 140 | `nickname` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '昵称', 141 | `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '邮箱', 142 | `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '电话', 143 | `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '地址', 144 | `create_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', 145 | `role` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '角色', 146 | PRIMARY KEY (`id`) USING BTREE 147 | ) ENGINE = InnoDB AUTO_INCREMENT = 31 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic; 148 | 149 | -- ---------------------------- 150 | -- Records of sys_user 151 | -- ---------------------------- 152 | INSERT INTO `sys_user` (id,username,password,nickname,email,phone,address,role) VALUES (1, 'admin', 'admin', 'admin', 'admin@qq.com', '13988997788', '安徽合肥', '2022-01-22 21:10:27', 'ROLE_ADMIN'); 153 | 154 | 155 | 156 | 157 | --------------------------------------------------------------------------------