在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个字符之间");
}
// 处理请求
}
无论使用哪种方式进行参数校验,都应该确保在处理请求之前进行校验,以确保数据的正确性和安全性。