Springboot2+vue2整合项目

张春  金牌会员 | 2024-5-17 03:45:52 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 905|帖子 905|积分 2715

前端

https://blog.csdn.net/m0_37613503/article/details/128961447
数据库

1.用户表
  1. CREATE TABLE `x_user` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `username` varchar(50) NOT NULL,
  4.   `password` varchar(100) DEFAULT NULL,
  5.   `email` varchar(50) DEFAULT NULL,
  6.   `phone` varchar(20) DEFAULT NULL,
  7.   `status` int(1) DEFAULT NULL,
  8.   `avatar` varchar(200) DEFAULT NULL,
  9.    `deleted` INT(1) DEFAULT 0,
  10.   PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
复制代码
  1. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('1','admin','123456','super@aliyun.com','18677778888','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
  2. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('2','zhangsan','123456','zhangsan@gmail.com','13966667777','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
  3. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('3','lisi','123456','lisi@gmail.com','13966667778','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
  4. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('4','wangwu','123456','wangwu@gmail.com','13966667772','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
  5. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('5','zhaoer','123456','zhaoer@gmail.com','13966667776','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
  6. insert into `x_user` (`id`, `username`, `password`, `email`, `phone`, `status`, `avatar`, `deleted`) values('6','songliu','123456','songliu@gmail.com','13966667771','1','https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif','0');
复制代码
2.角色表
  1. CREATE TABLE `x_role` (
  2.   `role_id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `role_name` varchar(50) DEFAULT NULL,
  4.   `role_desc` varchar(100) DEFAULT NULL,
  5.   PRIMARY KEY (`role_id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
复制代码
  1. insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('1','admin','超级管理员');
  2. insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('2','hr','人事专员');
  3. insert into `x_role` (`role_id`, `role_name`, `role_desc`) values('3','normal','普通员工');
复制代码
3.菜单表
  1. CREATE TABLE `x_menu` (
  2.   `menu_id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `component` varchar(100) DEFAULT NULL,
  4.   `path` varchar(100) DEFAULT NULL,
  5.   `redirect` varchar(100) DEFAULT NULL,
  6.   `name` varchar(100) DEFAULT NULL,
  7.   `title` varchar(100) DEFAULT NULL,
  8.   `icon` varchar(100) DEFAULT NULL,
  9.   `parent_id` int(11) DEFAULT NULL,
  10.   `is_leaf` varchar(1) DEFAULT NULL,
  11.   `hidden` tinyint(1) DEFAULT NULL,
  12.   PRIMARY KEY (`menu_id`)
  13. ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;
复制代码
  1. insert  into `x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`) values (1,'Layout','/user','/user/list','userManage','用户管理','userManage',0,'N',0),(2,'user/user','list',NULL,'userList','用户列表','userList',1,'Y',0),(3,'user/role','role',NULL,'roleList','角色列表','role',1,'Y',0),(4,'user/permission','permission',NULL,'permissionList','权限列表','permission',1,'Y',0);
复制代码
4.用户角色映射表
  1. CREATE TABLE `x_user_role` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `user_id` int(11) DEFAULT NULL,
  4.   `role_id` int(11) DEFAULT NULL,
  5.   PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
复制代码
  1. insert into `x_user_role` (`id`, `user_id`, `role_id`) values('1','1','1');
复制代码
5.角色菜单映射表
  1. CREATE TABLE `x_role_menu` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `role_id` int(11) DEFAULT NULL,
  4.   `menu_id` int(11) DEFAULT NULL,
  5.   PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
复制代码
后端

1、创建springboot项目2.6.13

2、pom依赖
  1.         <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-web</artifactId>
  4.         </dependency>
  5.         
  6.         <dependency>
  7.             <groupId>mysql</groupId>
  8.             <artifactId>mysql-connector-java</artifactId>
  9.         </dependency>
  10.         
  11.         <dependency>
  12.             <groupId>com.baomidou</groupId>
  13.             <artifactId>mybatis-plus-boot-starter</artifactId>
  14.             <version>3.5.2</version>
  15.         </dependency>
  16.         <dependency>
  17.             <groupId>com.baomidou</groupId>
  18.             <artifactId>mybatis-plus-generator</artifactId>
  19.             <version>3.5.2</version>
  20.         </dependency>
  21.         
  22.         <dependency>
  23.             <groupId>org.freemarker</groupId>
  24.             <artifactId>freemarker</artifactId>
  25.         </dependency>
  26.         
  27.         <dependency>
  28.             <groupId>org.projectlombok</groupId>
  29.             <artifactId>lombok</artifactId>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>org.springframework.boot</groupId>
  33.             <artifactId>spring-boot-starter-data-redis</artifactId>
  34.         </dependency>
复制代码
3.yml
  1. server:
  2.   port: 9999
  3. spring:
  4.   datasource:
  5.     username: root
  6.     password: 123456
  7.     url: jdbc:mysql://localhost:3306/xdb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT
  8.   redis:
  9.     port: 6379
  10.     host: localhost
  11. logging:
  12.   level:
  13.     com.zhu: debug
复制代码
2、Mybatis-plus代码天生

1.编写代码天生器
  1. package com.zhu;
  2. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
  3. import com.baomidou.mybatisplus.generator.config.OutputFile;
  4. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  5. import java.util.Collections;
  6. public class CodeGenerator {
  7.     public static void main(String[] args) {
  8.         String url = "jdbc:mysql://localhost:3306/xdb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT";
  9.         String username = "root";
  10.         String password = "123456";
  11.         String moduleName = "sys";
  12.         String mapperLocation = "E:\\Intellij IDEA\\项目\\x-admin\\src\\main\\resources\\mapper\"+ moduleName;
  13.         String tables = "x_user,x_menu,x_role,x_role_menu,x_user_role";
  14.         FastAutoGenerator.create(url, username, password)
  15.                 .globalConfig(builder -> {
  16.                     builder.author("zhutieyang") // 设置作者
  17.                             //.enableSwagger() // 开启 swagger 模式
  18.                             .fileOverride() // 覆盖已生成文件
  19.                             .outputDir("E:\\Intellij IDEA\\项目\\x-admin\\src\\main\\java"); // 指定输出目录
  20.                 })
  21.                 .packageConfig(builder -> {
  22.                     builder.parent("com.zhu") // 设置父包名
  23.                             .moduleName(moduleName) // 设置父包模块名
  24.                             .pathInfo(Collections.singletonMap(OutputFile.xml, mapperLocation)); // 设置mapperXml生成路径
  25.                 })
  26.                 .strategyConfig(builder -> {
  27.                     builder.addInclude(tables) // 设置需要生成的表名
  28.                             .addTablePrefix("x_"); // 设置过滤表前缀
  29.                 })
  30.                 .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
  31.                 .execute();
  32.     }
  33. }
复制代码

2、启动类加注解

因为自动天生的时候没有@mapper

3、测试


3、公共响应类
  1. package com.zhu.common;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @AllArgsConstructor
  7. @NoArgsConstructor
  8. public class Result<T> {
  9.     private Integer code;
  10.     private String message;
  11.     private T  data;
  12.     public static <T> Result<T> success(){
  13.         return new Result<>(20000,"success",null);
  14.     }
  15.     public static <T> Result<T> success(T data){
  16.         return new Result<>(20000,"success",data);
  17.     }
  18.     public static <T> Result<T> success(T data,String message){
  19.         return new Result<>(20000,message,data);
  20.     }
  21.     public static <T> Result<T> success(String message){
  22.         return new Result<>(20000,message,null);
  23.     }
  24.     public static<T>  Result<T> fail(){
  25.         return new Result<>(20001,"fail",null);
  26.     }
  27.     public static<T>  Result<T> fail(Integer code){
  28.         return new Result<>(code,"fail",null);
  29.     }
  30.     public static<T>  Result<T> fail(Integer code, String message){
  31.         return new Result<>(code,message,null);
  32.     }
  33.     public static<T>  Result<T> fail( String message){
  34.         return new Result<>(20001,message,null);
  35.     }
  36. }
复制代码


4.登录相关接口

4.1、登录


controller
  1. @PostMapping("/login")
  2.     public Result<Map<String,Object>> login(@RequestBody User user){
  3.         Map<String,Object>  data = userService.login(user);
  4.         if(data !=null){
  5.             return Result.success(data);
  6.         }
  7.         return Result.fail(20002,"用户名或密码错误");
  8.     }
复制代码
service
  1. package com.zhu.sys.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.zhu.config.MyRedisConfig;
  4. import com.zhu.sys.entity.User;
  5. import com.zhu.sys.mapper.UserMapper;
  6. import com.zhu.sys.service.IUserService;
  7. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  8. import org.omg.CORBA.TIMEOUT;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.stereotype.Service;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. import java.util.UUID;
  15. import java.util.concurrent.TimeUnit;
  16. /**
  17. * <p>
  18. *  服务实现类
  19. * </p>
  20. *
  21. * @author zhutieyang
  22. * @since 2024-04-06
  23. */
  24. @Service
  25. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
  26.     @Autowired
  27.     private RedisTemplate redisTemplate;
  28.     @Override
  29.     public Map<String, Object> login(User user) {
  30.         // 根据用户名和密码去查询
  31.         LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
  32.         wrapper.eq(User::getUsername,user.getUsername());
  33.         wrapper.eq(User::getPassword,user.getPassword());
  34.         User loginUser = this.baseMapper.selectOne(wrapper);
  35.         // 结果不为空,则生成token,并将用户信息存入redis
  36.         if(loginUser !=null){
  37.             // 暂时用UUID,终极方案是jwt
  38.            String key ="user:"+ UUID.randomUUID();
  39.            // 存入redis
  40.             loginUser.setPassword(null);
  41.             redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);
  42.             // 返回数据
  43.             Map<String, Object> data = new HashMap<>();
  44.             data.put("token",key);
  45.             return data;
  46.         }
  47.         return null;
  48.     }
  49. }
复制代码
4.1.2、整合redis

1.pom
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
复制代码
2.yml
  1. spring:
  2.   redis:
  3.     host: localhost
  4.     port: 6379
复制代码
3.设置类
  1. package com.zhu.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.JsonInclude;
  4. import com.fasterxml.jackson.annotation.JsonTypeInfo;
  5. import com.fasterxml.jackson.annotation.PropertyAccessor;
  6. import com.fasterxml.jackson.databind.DeserializationFeature;
  7. import com.fasterxml.jackson.databind.MapperFeature;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. import com.fasterxml.jackson.databind.SerializationFeature;
  10. import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.context.annotation.Bean;
  13. import org.springframework.context.annotation.Configuration;
  14. import org.springframework.data.redis.connection.RedisConnectionFactory;
  15. import org.springframework.data.redis.core.RedisTemplate;
  16. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import org.springframework.stereotype.Controller;
  19. import javax.annotation.Resource;
  20. import java.text.SimpleDateFormat;
  21. import java.util.TimeZone;
  22. @Configuration
  23. public class MyRedisConfig {
  24.     @Resource
  25.     private RedisConnectionFactory factory;
  26.     @Bean
  27.     public RedisTemplate redisTemplate(){
  28.         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  29.         redisTemplate.setConnectionFactory(factory);
  30.         redisTemplate.setKeySerializer(new StringRedisSerializer());
  31.         Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
  32.         redisTemplate.setValueSerializer(serializer);
  33.         ObjectMapper om = new ObjectMapper();
  34.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  35.         om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
  36.         om.setTimeZone(TimeZone.getDefault());
  37.         om.configure(MapperFeature.USE_ANNOTATIONS, false);
  38.         om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  39.         om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  40.         om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  41.         om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  42.         serializer.setObjectMapper(om);
  43.         return redisTemplate;
  44.     }
  45. }
复制代码
4.2、获取用户信息


controller
  1. @GetMapping("/info")
  2.     public Result<?> getUserInfo(@Param("token") String token){
  3.         Map<String,Object> data = userService.getUserInfo(token);
  4.         if(data != null){
  5.             return Result.success(data);
  6.         }
  7.         return Result.fail(20003,"用户信息获取失败");
  8.     }
复制代码
service
  1. public Map<String, Object> getUserInfo(String token) {
  2.     // 从redis查询token
  3.     Object obj = redisTemplate.opsForValue().get(token);
  4.     // 反序列化
  5.     User user = JSON.parseObject(JSON.toJSONString(obj),User.class);
  6.     if(user != null){
  7.         Map<String, Object> data =  new HashMap<>();
  8.         data.put("name",user.getUsername());
  9.         data.put("avatar",user.getAvatar());
  10.         List<String> roleList = this.getBaseMapper().getRoleNamesByUserId(user.getId());
  11.         data.put("roles", roleList);
  12.         return data;
  13.     }
  14.     return null;
  15. }
复制代码
mapper.xml
  1. <select id="getRoleNamesByUserId" parameterType="Integer" resultType="String">
  2.     SELECT
  3.     b.role_name
  4.     FROM x_user_role a,x_role b
  5.     WHERE a.`user_id` = #{userId}
  6.     AND a.`role_id` = b.`role_id`
  7. </select>
复制代码
4.3、注销


controller
  1. @PostMapping("/logout")
  2. public Result<?> logout(@RequestHeader("X-Token") String token){
  3.     userService.logout(token);
  4.     return Result.success("注销成功");
  5. }
复制代码
service
  1. public void logout(String token) {
  2.     redisTemplate.delete(token);
  3. }
复制代码
5、跨域处理

记得打开redis
  1. package com.zhu.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.cors.CorsConfiguration;
  5. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  6. import org.springframework.web.filter.CorsFilter;
  7. @Configuration
  8. public class MyCorsConfig {
  9.     @Bean
  10.     public CorsFilter corsFilter(){
  11.         //添加CORS配置信息
  12.         CorsConfiguration configuration = new CorsConfiguration();
  13.         //允许的域,不要写*,否则cookie就无法使用了
  14.         configuration.addAllowedOrigin("http://localhost:8888");//这里填写请求的前端服务器
  15.         //是否发送Cookie信息
  16.         configuration.setAllowCredentials(true);
  17.         //允许的请求方式
  18.         configuration.addAllowedMethod("*");
  19.         // 4)允许的头信息
  20.         configuration.addAllowedHeader("*");
  21.         // 添加映射路径,我们拦截一切请求
  22.         UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
  23.         urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",configuration);
  24.         //返回新的CorsFilter
  25.         return new CorsFilter(urlBasedCorsConfigurationSource);
  26.     }
  27. }
复制代码
6、用户管理接口


6.1、查询用户列表

1、controller
  1. @GetMapping("/list")
  2.     public Result<Map<String,Object>> getUserList(@RequestParam(value = "username",required = false) String username,
  3.                                               @RequestParam(value = "phone",required = false) String phone,
  4.                                               @RequestParam(value = "pageNo") Long pageNo,
  5.                                               @RequestParam(value = "pageSize") Long pageSize){
  6.         LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
  7.         wrapper.eq(StringUtils.hasLength(username),User::getUsername,username);
  8.         wrapper.eq(StringUtils.hasLength(phone),User::getPhone,phone);
  9.         Page<User> page = new Page<>(pageNo,pageSize);
  10.         userService.page(page,wrapper);
  11.         Map<String,Object> data = new HashMap<>();
  12.         data.put("total",page.getTotal());
  13.         data.put("rows",page.getRecords());
  14.         return Result.success(data);
复制代码
2、分页拦截器
  1. @Configuration
  2. public class MpConfig {
  3.     @Bean
  4.     public MybatisPlusInterceptor mybatisPlusInterceptor() {
  5.         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  6.         interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  7.         return interceptor;
  8.     }
  9. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张春

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表