添加依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.12.RELEASE com.hzk springboot-vue1 0.0.1-SNAPSHOT springboot-vue1 Demo project for Spring Boot 1.8 com.baomidou mybatis-plus-generator 3.5.2 org.freemarker freemarker 2.3.31 com.baomidou mybatis-plus-boot-starter 3.5.2 com.alibaba druid-spring-boot-starter 1.2.8 com.github.xiaoymin swagger-bootstrap-ui 1.9.6 com.spring4all swagger-spring-boot-starter 1.9.1.RELEASE org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 mysql mysql-connector-java runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
使用代码生成器
package com.hzk; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.Collections; public class Generator { public static void main(String[] args) { FastAutoGenerator.create("jdbc:mysql://localhost:3306/acl_permission?serverTimezone=Asia/Shanghai", "root", "123456") .globalConfig(builder -> { builder.author("刘德华") // 设置作者 .enableSwagger() // 开启 swagger 模式 .fileOverride() // 覆盖已生成文件 .outputDir(".\src\main\java\"); // 指定输出目录 }) .packageConfig(builder -> { builder.parent("com.hzk") // 设置父包名 .moduleName("system") // 设置父包模块名 .pathInfo(Collections.singletonMap(OutputFile.xml, "src\main\resources\mapper\")); // 设置mapperXml生成路径 }) .strategyConfig(builder -> { builder.addInclude("acl_user","acl_role","acl_permission")// 设置需要生成的表名 .addTablePrefix("acl_"); // 设置过滤表前缀 }) .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板 .execute(); } }
加入代码生成器的依赖
com.baomidou mybatis-plus-generator 3.5.2 org.freemarker freemarker 2.3.31
执行代码生成器
加入swagger依赖
com.github.xiaoymin swagger-bootstrap-ui 1.9.6 com.spring4all swagger-spring-boot-starter 1.9.1.RELEASE
配置application文件
server.port=8807 spring.datasource.druid.url=jdbc:mysql://localhost:3306/acl_permission?serverTimezone=Asia/Shanghai spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.druid.username=root spring.datasource.druid.password=123456 #日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
写接口
1.创建vo包
创建接收参数的实体类
登录接口
package com.hzk.system.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.hzk.system.entity.User; import com.hzk.system.service.IUserService; import com.hzk.system.vo.CommonResult; import com.hzk.system.vo.LoginVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/system") public class LoginController { @Autowired private IUserService userService; @PostMapping("/login") public CommonResult login(@RequestBody LoginVo loginVo){ QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("username",loginVo.getName()); wrapper.eq("password",loginVo.getPassword()); wrapper.eq("is_deleted",0); User user = userService.getOne(wrapper); if (user!=null){ return new CommonResult(2000,"登录成功",null); }else { return new CommonResult(5000,"登录失败",null); } } }
开启mapperscan
加入swagger配置类
package com.hzk.system.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import java.util.ArrayList; @Configuration public class SwaggerConfig { @Bean//swagger中所有的功能都封装在Docket类中 public Docket docket(){ Docket docket = new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo())//设置api文档消息 .select() .apis(RequestHandlerSelectors.basePackage("com.hzk.system.controller"))//指定为哪些包下的类生成接口文档 .build(); return docket; } private ApiInfo apiInfo(){ Contact DEFAULT_CONTACT = new Contact("刘德华", "www.baidu.com", "120@.com"); ApiInfo apiInfo = new ApiInfo("hzk在线文档", "马德华的文档", "H1.0", "www.hzk.com", DEFAULT_CONTACT, "志远科技", "http://www.sohu.com", new ArrayList()); return apiInfo; } }
开启swagger
运行进入swagger文档
加描述
前端调用后端登录接口时出现如下的错误
Access-Control-Allow-Origin’ header is present on the requested resource.
为跨域问题:
当使用异步请求从一个网址访问另一个网址时可能会出现跨域问题。
前提:
- 必须为异步请求
- 当端口号或协议或ip不同时则会出现跨域
出现两个请求: 有一个请求的方式为: OPTIONS 和真实的请求方式
理解: OPTIONS先头部队。—探视后台有没有解决跨域。
如何解决跨域:
(1)直接在控制添加注释
(origins = {“192.168.0.111:8080”,“192.168.0.120:8081”},allowedHeaders=“运行哪些请求头跨域”,methods={“GET”,“POST”})
origins: 允许哪些域可以跨域访问我这个接口
allowedHeaders:允许哪些请求头信息跨域
methods: 允许哪些请求方式跨域
(2)添加配置类,全局配置
package com.hzk.system.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { // 当前跨域请求最大有效时长。这里默认1天 private static final long MAX_AGE = 24 * 60 * 60; @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 corsConfiguration.setMaxAge(MAX_AGE); source.registerCorsConfiguration(" @Configuration public class RedisConfig { @Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate<>(); RedisSerializer redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 filed value template.setHashValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(redisSerializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题),过期时间600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化 .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
前端添加代码
测试登录
后面每次请求都可以携带该token,
每次请求都得要人为添加参数token. 我们可以使用axios得请求拦截器。
写接口
进行测试
出现LocalDateTime序列化异常:Cannot construct instance of java.time.LocalDateTime
解决办法
加依赖
com.fasterxml.jackson.datatype jackson-datatype-jsr310 2.13.0
加注释
再进行测试
前置路由守卫
前置路由守卫:就是在路由跳转前加上自己得一些业务代码。
//设置前置路由守卫 to:到哪个路由 from:从哪个路由来 next():放行到指定路由 router.beforeEach((to,from,next)=>{ //获取跳转得路径 var path = to.path; //判断是否为登录路由路径 if(path==="/login"){ console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") //放行 return next(); } //其他路由路径 判断是否登录过 var token = sessionStorage.getItem("token"); if(token){ return next(); } //跳转登录 return next("/login"); })
后端代码全部依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.12.RELEASE com.hzk springboot-vue1 0.0.1-SNAPSHOT springboot-vue1 Demo project for Spring Boot 1.8 com.baomidou mybatis-plus-generator 3.5.2 org.freemarker freemarker 2.3.31 com.baomidou mybatis-plus-boot-starter 3.5.2 com.alibaba druid-spring-boot-starter 1.2.8 com.github.xiaoymin swagger-bootstrap-ui 1.9.6 com.spring4all swagger-spring-boot-starter 1.9.1.RELEASE org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 mysql mysql-connector-java runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.github.xiaoymin swagger-bootstrap-ui 1.9.6 com.spring4all swagger-spring-boot-starter 1.9.1.RELEASE org.springframework.boot spring-boot-starter-data-redis com.fasterxml.jackson.datatype jackson-datatype-jsr310 2.13.0 org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok