在Java中,對于GET方法的參數校驗,通常可以采用以下幾種方式:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotNull(message = "用戶名不能為空")
private String username;
@Size(min = 6, max = 20, message = "密碼長度必須在6到20個字符之間")
private String password;
}
在需要校驗的地方,你可以使用Validator
對象進行校驗:
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
public class Main {
public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
User user = new User(); // 創建一個User對象,設置屬性值
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (!violations.isEmpty()) {
// 處理校驗失敗的情況
}
}
}
@Validated
注解,Spring會自動進行參數校驗。例如:import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@RestController
@Validated
public class UserController {
@GetMapping("/getUser")
public User getUser(@RequestParam("username") @NotNull(message = "用戶名不能為空") String username,
@RequestParam("password") @Size(min = 6, max = 20, message = "密碼長度必須在6到20個字符之間") String password) {
// 處理請求
}
}
public User getUser(String username, String password) {
if (username == null || username.trim().isEmpty()) {
throw new IllegalArgumentException("用戶名不能為空");
}
if (password == null || password.length() < 6 || password.length() > 20) {
throw new IllegalArgumentException("密碼長度必須在6到20個字符之間");
}
// 處理請求
}
無論使用哪種方式進行參數校驗,都應該確保在處理請求之前進行校驗,以確保數據的正確性和安全性。