From e743dbc2d06f1d5484959545593415c29c2c4ab5 Mon Sep 17 00:00:00 2001 From: Unique-Jerry <10902054+unique-jerry@user.noreply.gitee.com> Date: Fri, 13 Oct 2023 21:50:21 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E4=BB=93=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/encodings.xml | 1 + pom.xml | 38 +++++++++- .../AiInterviewer/config/RedisConfig.java | 40 +++++++++++ .../AiInterviewer/config/SwaggerConfig.java | 55 ++++++++++++++ .../AiInterviewer/config/UserInterceptor.java | 51 +++++++++++++ .../AiInterviewer/config/WebMvcConfig.java | 27 +++++++ .../controller/HelloController.java | 36 ++++++++++ .../com/yzdx/AiInterviewer/entity/User.java | 12 ++++ .../com/yzdx/AiInterviewer/utiles/JWT.java | 68 ++++++++++++++++++ .../yzdx/AiInterviewer/utiles/RedisUtil.java | 72 +++++++++++++++++++ src/main/resources/application.properties | 13 ---- src/main/resources/application.yml | 24 +++++++ target/classes/application.properties | 13 ---- 13 files changed, 422 insertions(+), 28 deletions(-) create mode 100644 src/main/java/com/yzdx/AiInterviewer/config/RedisConfig.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/config/SwaggerConfig.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/config/UserInterceptor.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/config/WebMvcConfig.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/controller/HelloController.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/entity/User.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/utiles/JWT.java create mode 100644 src/main/java/com/yzdx/AiInterviewer/utiles/RedisUtil.java delete mode 100644 src/main/resources/application.properties create mode 100644 src/main/resources/application.yml delete mode 100644 target/classes/application.properties diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 63e9001..aa00ffa 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -2,5 +2,6 @@ + \ No newline at end of file diff --git a/pom.xml b/pom.xml index eb4aeb6..30fc772 100644 --- a/pom.xml +++ b/pom.xml @@ -11,10 +11,11 @@ - spring-boot-starter-parent org.springframework.boot + spring-boot-starter-parent 2.6.6 - + + @@ -56,6 +57,39 @@ mysql-connector-java + + + io.springfox + springfox-swagger2 + 2.6.1 + + + + io.springfox + springfox-swagger-ui + 2.6.1 + + + + com.auth0 + java-jwt + 3.4.0 + + + + + redis.clients + jedis + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.apache.commons + commons-pool2 + diff --git a/src/main/java/com/yzdx/AiInterviewer/config/RedisConfig.java b/src/main/java/com/yzdx/AiInterviewer/config/RedisConfig.java new file mode 100644 index 0000000..4b78a30 --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/config/RedisConfig.java @@ -0,0 +1,40 @@ +package com.yzdx.AiInterviewer.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; + +/** + * @ClassName redisConfig + * @Description TODO + * @Author 加辣椒了吗? + * @Date 2022/4/28 2:33 + * @Version 1.0 + **/ +@Configuration +public class RedisConfig { + @Bean + public RedisTemplate redisTemplate(RedisConnectionFactory factory){ + // 将redis注入工厂 + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // 设置key的序列化方式 + template.setKeySerializer (RedisSerializer.string()); + //设置value的序列化方式 + template.setValueSerializer (RedisSerializer.json()); + // 设置hash的key的序列化方式 + template. setHashKeySerializer (RedisSerializer.string()); + // 设置hash的value的序列化方式 + template.setHashValueSerializer (RedisSerializer.json()); + // 使设置生效 + template.afterPropertiesSet(); + + return template; + } +} + + + diff --git a/src/main/java/com/yzdx/AiInterviewer/config/SwaggerConfig.java b/src/main/java/com/yzdx/AiInterviewer/config/SwaggerConfig.java new file mode 100644 index 0000000..5907fe1 --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/config/SwaggerConfig.java @@ -0,0 +1,55 @@ +package com.yzdx.AiInterviewer.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; +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 springfox.documentation.swagger2.annotations.EnableSwagger2; + +import java.util.ArrayList; + + +@Configuration +@EnableSwagger2 //开启swagger2 +public class SwaggerConfig { + + //配置了Swagger 的Docker的bean实例 + @Bean + public Docket docket(Environment environment){ + + //设置要显示的Swagger环境 + Profiles profiles =Profiles.of("dev","test"); + //判断是否处于开发环境下 + boolean flag=environment.acceptsProfiles(profiles); + + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .enable(flag) + .select() + .apis(RequestHandlerSelectors.basePackage("com.yzdx.AiInterviewer.controller")) + .build() + ; + } + //配置Swagger信息=apiInfo + private ApiInfo apiInfo(){ + + Contact contact=new Contact("扬州大学开发团队", "http://www.yzu.edu.cn/", "2209176490@qq.com"); + + return new ApiInfo( + "Ai-Interviewer API开发文档", + "再小的帆也能远航", + "1.0", + "urn:tos", + contact, + "Apache 2.0", + "http://www.apache.org/licenses/LICENSE-2.0" + + ); + + } +} \ No newline at end of file diff --git a/src/main/java/com/yzdx/AiInterviewer/config/UserInterceptor.java b/src/main/java/com/yzdx/AiInterviewer/config/UserInterceptor.java new file mode 100644 index 0000000..61805c9 --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/config/UserInterceptor.java @@ -0,0 +1,51 @@ +package com.yzdx.AiInterviewer.config; + +import com.auth0.jwt.exceptions.AlgorithmMismatchException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.yzdx.AiInterviewer.utiles.JWT; +import net.minidev.json.JSONObject; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +/** + * @Description: 拦截器 + * @Author: 新写的旧代码 + * @CreateTime: 2022/3/24 + */ +public class UserInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + Map map = new HashMap<>(); + + String Token = request.getHeader("Authorization"); + + // 捕获刚刚JWT中抛出的异常,并封装对应的返回信息 + try { + JWT.verifyToken(Token); + return true; + }catch (SignatureVerificationException e){ + map.put("msg", "无效签名"); + }catch (TokenExpiredException e){ + map.put("msg", "已过期"); + }catch (AlgorithmMismatchException e){ + map.put("msg", "算法不一致"); + }catch (Exception e){ + map.put("msg", "无效身份信息"); + } + // 封装返回值 + map.put("code", 401); + JSONObject json = new JSONObject(map); + response.setContentType("application/json;charset=UTF-8"); + PrintWriter writer = response.getWriter(); + writer.print(json); + writer.flush(); + writer.close(); + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/yzdx/AiInterviewer/config/WebMvcConfig.java b/src/main/java/com/yzdx/AiInterviewer/config/WebMvcConfig.java new file mode 100644 index 0000000..0f08f6f --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/config/WebMvcConfig.java @@ -0,0 +1,27 @@ +package com.yzdx.AiInterviewer.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @Description: springMVC配置 + * @Author: 新写的旧代码 + * @CreateTime: 2022/3/24 + */ + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + @Override + public void addInterceptors(InterceptorRegistry registry) { + // 用户拦截器 + registry.addInterceptor(new com.yzdx.AiInterviewer.config.UserInterceptor()) + // 需要拦截的请求 + .addPathPatterns("/**") + // 需要放行的请求 + .excludePathPatterns("/user/login","/user/register","/user/sendCode") + // 添加swagger-ui的放行路径 + .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","/doc.html/**") + ; + } +} \ No newline at end of file diff --git a/src/main/java/com/yzdx/AiInterviewer/controller/HelloController.java b/src/main/java/com/yzdx/AiInterviewer/controller/HelloController.java new file mode 100644 index 0000000..c5b9b02 --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/controller/HelloController.java @@ -0,0 +1,36 @@ +package com.yzdx.AiInterviewer.controller; + +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/hello") +public class HelloController { + + @GetMapping("/hello") + public String hello(){ + return "hello"; + } + + @ApiOperation("用户登录") + @PostMapping("/test") + public Map testLogin(@ApiParam("用户名") String username ,@ApiParam("密码")String password){ + + + Map result=new HashMap<>(); + + result.put("code",0); + result.put("message","登陆成功"); + result.put("data","username:"+username+","+"password:"+password); + + return result; + + } +} diff --git a/src/main/java/com/yzdx/AiInterviewer/entity/User.java b/src/main/java/com/yzdx/AiInterviewer/entity/User.java new file mode 100644 index 0000000..83ef36f --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/entity/User.java @@ -0,0 +1,12 @@ +package com.yzdx.AiInterviewer.entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel("用户实体类") +public class User { + @ApiModelProperty("用户名") + public String username; + @ApiModelProperty("密码") + public String password; +} diff --git a/src/main/java/com/yzdx/AiInterviewer/utiles/JWT.java b/src/main/java/com/yzdx/AiInterviewer/utiles/JWT.java new file mode 100644 index 0000000..56fff0b --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/utiles/JWT.java @@ -0,0 +1,68 @@ +package com.yzdx.AiInterviewer.utiles; + +import com.auth0.jwt.JWTCreator; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; + +import java.util.Calendar; + +/** + * @Author: 新写的旧代码 + * @Description: token生成 + * @CreateTime: 2022/3/24 + */ +public class JWT { + // 任意字符串 + private static final String SING = "xxxx@Jerry"; + + private static String token; + + // get and set + public static String getToken() { + return token; + } + public static void setToken(String token) { + JWT.token = token; + } + + // 生成用户token + public static String getJWToken(Integer id){ + + Calendar instance = Calendar.getInstance(); + // 设置过期时间,这里设置的是一天 + instance.add(Calendar.DATE,30); + + JWTCreator.Builder builder = com.auth0.jwt.JWT.create(); + + // 指定标识字段 + builder.withClaim("lawyerId", id); + + // 指定过期时间 + token = builder.withExpiresAt(instance.getTime()) + // 指定生成算法及签名 + .sign(Algorithm.HMAC256(SING)); + + return token; + } + + // 验证token,返回true或false + public static boolean verify(String token){ + try { + com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(token); + return true; + }catch (Exception e){ + return false; + } + } + + // 验证token,正确通过,否则抛出异常 + public static DecodedJWT verifyToken(String lawyerToken){ + return com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(lawyerToken); + } + + // 从token中获取用户id + public static int getTokenId(String token){ + DecodedJWT verify = com.auth0.jwt.JWT.require(Algorithm.HMAC256(SING)).build().verify(token); + return verify.getClaim("Id").asInt(); + } +} \ No newline at end of file diff --git a/src/main/java/com/yzdx/AiInterviewer/utiles/RedisUtil.java b/src/main/java/com/yzdx/AiInterviewer/utiles/RedisUtil.java new file mode 100644 index 0000000..33e6eca --- /dev/null +++ b/src/main/java/com/yzdx/AiInterviewer/utiles/RedisUtil.java @@ -0,0 +1,72 @@ +package com.yzdx.AiInterviewer.utiles; + +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.concurrent.TimeUnit; + +/** + * redis工具类 + */ +@Component +public class RedisUtil { + + @Resource + private RedisTemplate redisTemplate; + + // 指定缓存失效时间 + public Boolean expire(final String key, final long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (final Exception e) { + e.printStackTrace(); + return false; + } + } + + // 根据键获取值 + public Object get(final String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + // 将键值对存入redis + public Boolean set(final String key, final Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (final Exception e) { + e.printStackTrace(); + return false; + } + } + + // 将键值对存入value并设置过期时间 + public Boolean set(final String key, final Object value, final long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (final Exception e) { + e.printStackTrace(); + return false; + } + } + + // 删除键 + public Boolean del(final String key) { + try { + redisTemplate.opsForValue().getAndDelete(key); + return true; + } catch (final Exception e) { + e.printStackTrace(); + return false; + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index 289335d..0000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -1,13 +0,0 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai -spring.datasource.username=root -spring.datasource.password=root -mybatis.mapper-locations=classpath:mapper/*.xml -user.address.max-count=20 -# ��������ͻ��˲���ӦΪnull������ -spring.jackson.default-property-inclusion=NON_NULL - -##server.servlet.context-path=/store -spring.servlet.multipart.maxFileSize=10MB -spring.servlet.multipart.maxRequestSize=10MB - -server.port=80 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..6abe02c --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 80 + +spring: + datasource: + url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + username: root + password: root + + jackson: + default-property-inclusion: non_null + + mvc: + pathmatch: + matching-strategy: ant_path_matcher + +#dev //说明现在是开发环境 + profiles: + active: dev + + redis: + database: 11 + host: localhost + port: 6379 \ No newline at end of file diff --git a/target/classes/application.properties b/target/classes/application.properties deleted file mode 100644 index 289335d..0000000 --- a/target/classes/application.properties +++ /dev/null @@ -1,13 +0,0 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai -spring.datasource.username=root -spring.datasource.password=root -mybatis.mapper-locations=classpath:mapper/*.xml -user.address.max-count=20 -# ��������ͻ��˲���ӦΪnull������ -spring.jackson.default-property-inclusion=NON_NULL - -##server.servlet.context-path=/store -spring.servlet.multipart.maxFileSize=10MB -spring.servlet.multipart.maxRequestSize=10MB - -server.port=80 \ No newline at end of file