4.6日

springboot 在application.yml中定义数组的两种方式:
第一种是用@value
application.yml
e:
a:123
b:455
c:22
@Component
public class YmlProperties {

@Value("${e.a}")
public String a;


@Value("${e.b}")
public List b;

@Value("${e.c}")
public String c;

}

第二种
@ConfigurationProperties
application.yml:
e:
a:123
b:455
c:22
@Component
@ConfigurationProperties(prefix = "e")
public class YmlProperties {

@Value("${e.a}")
public String a;


@Value("${e.b}")
public List b;

@Value("${e.c}")
public String c;

}
@Validated放在controller外
public Result register(@Pattern(regexp = "^\S{5,16}$") String username, @Pattern(regexp = "^\S{5,16}$")String password){
if(username!=null && username.length()>=5 && username.length()<=16 &&password!=null && password.length()>=5 && password.length()<=16){
User u=userService.findByUsername(username);
if(u==null){
//没有占用
//完成注册
userService.register(username,password);
return Result.success();
}else{
//占用
return Result.error("用户名已被占用");
}
}else{
return Result.error("参数不合法");
}取消繁琐的参数校验username!=null && username.length()>=5 && username.length()<=16 &&password!=null && password.length()>=5 && password.length()<=16
JWT令牌加密
@Test
public void testGen(){
Map<String,Object> claims=new HashMap<>();
claims.put("id",1);
claims.put("username","张三");
String token=JWT.create()
.withClaim("user",claims)//添加载荷
.withExpiresAt(new Date(System.currentTimeMillis()+10006060*12))//添加过期时间
.sign(Algorithm.HMAC256("YZL"));//指定算法,配置秘钥
System.out.println(token);
}
@Test
public void testParse(){
String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3NDM5ODMyOTd9" +
".rZHItCJPQB2hLEB-HXuW2T-pjXKGXBJOuFgqiS-LPPQ";
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("YZL")).build();
DecodedJWT decodedJWT=jwtVerifier.verify(token);//验证token,生成一个解析后的JWT对象
Map<String,Claim> claims = decodedJWT.getClaims();
System.out.println(claims.get("user"));
}
//如果篡改了头部和载荷部分,那么验证失败
//如果秘钥改了,验证失败
//token过期
//载荷不可存放私密信息
加入依赖

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>4.4.0</version>
</dependency>

登录拦截器
@Configuration//注入ioc容器
public class WebConfig implements WebMvcConfigurer {
@Autowired
private Logininterceptor logininterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//登录和注册接口不拦截
registry.addInterceptor(logininterceptor).excludePathPatterns("/user/login","/user/register");
}
}
excludePathPatterns("/user/login","/user/register")放行这两个接口

posted @ 2025-04-06 20:52  YANGzLIN...11  阅读(41)  评论(0)    收藏  举报