項目隨筆-【大事件(文章類)】 自定義參數校驗註解 需要寫一個自定義註解Xxx+校驗規則的類XxxValidation【需要繼承ConstraintValidator】 自定義註解 @Documented @Target(ElementType.FIELD) @Retention(Retention ...
項目隨筆-【大事件(文章類)】
自定義參數校驗註解
需要寫一個自定義註解Xxx+校驗規則的類XxxValidation【需要繼承ConstraintValidator】
自定義註解
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {StateValidation.class})//使用 `StateValidation` 類來驗證該欄位的值是否滿足特定的約束條件
public @interface State {
String message() default "state參數的值只能是已發佈或者草稿";//驗證失敗的錯誤提示信息
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
註解校驗規則
public class StateValidation implements ConstraintValidator<State,String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
//校驗規則
if (value == null){
return false;
}
if (value.equals("已發佈") || value.equals("草稿")){
return true;
}
return false;
}
}
<State>
是ConstraintValidator
介面的第一個泛型參數,它指定了驗證器將要驗證的約束註解的類型。在這個例子中,State
可能是一個自定義的註解,用於標記需要驗證的欄位。<String>
是ConstraintValidator
介面的第二個泛型參數,它指定了驗證器將要驗證的屬性值的類型。在這個例子中,String
表示StateValidation
類將驗證String
類型的屬性值。
阿裡雲Oss存儲
工具類
public class AliOssUtil {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環境變數中獲取訪問憑證。運行本代碼示例之前,請確保已設置環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。【這裡沒使用】
// EnvironmentVariableCredentialsProvider credentialsProvider =
// CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
private static final String ACCESS_KEY_ID = "LTAI5tJKk5H98ZmQQ9CgeG8y";
private static final String ACCESS_KEY_SECRET = "90xHhXxKig6LNnbb4ubpRBeIdw7RAT";
// 填寫Bucket名稱,例如examplebucket。
private static final String BUCKET_NAME = "zy-bigevent";
public static String uploadFile(String objectName, InputStream in) throws Exception {
// 填寫Object完整路徑,完整路徑中不能包含Bucket名稱,例如exampledir/exampleobject.txt。
// 創建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
String url = "";
try {
// 填寫字元串。
String content = "Hello OSS,你好世界";
// 創建PutObjectRequest對象。
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, in);
// 如果需要上傳時設置存儲類型和訪問許可權,請參考以下示例代碼。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上傳字元串。
PutObjectResult result = ossClient.putObject(putObjectRequest);
url = "https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}
}
Controller
@RestController
public class FileUploadController {
@PostMapping("/upload")
public Result<String> upload(MultipartFile file) throws Exception {
//把文件的內容存儲到本地磁碟
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
// file.transferTo(new File("C:\\Users\\23117\\Desktop\\files\\"+originalFilename));
String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
return Result.success(url);
}
}
Redis主動失效令牌
令牌主動失效機制
● 登錄成功後,給瀏覽器響應令牌的同時,把該令牌存儲到redis中。
● LoginInterceptor攔截器中,需要驗證瀏覽器攜帶的令牌,並同時需要獲取到redis中存儲的與之相同的令牌。
● 當用戶修改密碼成功後,刪除redis中存儲的舊令牌。
登錄
@PostMapping("/login")
public Result<String> login(String username,String password) {
//業務邏輯...
String token = JwtUtil.genToken(claims);
//把 token 存儲到 redis 中
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//redis存儲令牌 key 和 value 都是 token
operations.set(token,token,1, TimeUnit.HOURS);//TimeUnit.HOURS 是 redis key 的過期時間單位
return Result.success(token);
//業務邏輯...
}
更換密碼【此時需要主動刪除redis中的token】
@PatchMapping("/updatePwd")
public Result updatePwd(@RequestBody Map<String, String> parms,@RequestHeader("Authorization") String token) {
//業務邏輯...
userService.updatePwd(newPwd);//更新新密碼
//刪除redis對應的token
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.getOperations().delete(token);
return Result.success();
}
攔截器
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//令牌驗證
String token = request.getHeader("Authorization");
try {
//獲取redid key
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
String redisToken = operations.get(token);
if (redisToken == null){
//token 已經失效
throw new RuntimeException();
}
Map<String, Object> claims = JwtUtil.parseToken(token);
ThreadLocalUtil.set(claims);
//放行
return true;
} catch (Exception e) {
response.setStatus(401);
//不放行
return false;
}
}
SpringBoot項目部署
需要pom.xml文件加入打包插件
<build>
<plugins>
<!-- 打包插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</build>
在maven生命周期中點擊 package生成jar
在對應環境部署 java -jar 【 jar的名字 】
SpringBoot配置方式
SpringBoot多環境開發
- SpringBoot多環境開發需要分開發環境、測試環境、生產環境
SpringBoot多環境開發單文件配置
#通用信息,指定生效的環境
spring:
profiles:
active: dev
server:
servlet:
context-path: /aaa
---
#開發環境
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/big_event
username: root
password: zy
servlet:
multipart:
max-file-size: 5MB
data:
redis:
host: localhost
port: 6379
config:
activate:
on-profile: dev
mybatis:
configuration:
map-underscore-to-camel-case: true #開啟駝峰命名/下劃線命名轉換
server:
port: 8081
---
#測試環境
spring:
config:
activate:
on-profile: test
server:
port: 8082
---
#生產環境
spring:
config:
activate:
on-profile: pro
server:
port: 8084
SpringBoot多環境開發多文件配置
application.yml
#通用信息,指定生效的環境
spring:
profiles:
active: test
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/big_event
username: root
password: zy
server:
servlet:
context-path: /aaa
application-dev.yml
#開發環境
config:
activate:
on-profile: dev
server:
port: 8081
application-pro.yml
#生產環境
spring:
config:
activate:
on-profile: pro
server:
port: 8084
application-test.yml
#測試環境
spring:
config:
activate:
on-profile: test
server:
port: 8082
SpringBoot多環境開發多文件配置-分組
application.yml
#通用信息,指定生效的環境
spring:
profiles:
group:
"dev": devService,devDB,devSelf
active: dev
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/big_event
username: root
password: zy
server:
servlet:
context-path: /aaa
application-devService
#開發環境
server:
port: 8085
application-devDb
#資料庫相關配置
application-devSelf
#自定義相關配置
項目參考:
B站:BV14z4y1N7pg