
首先,我们需要创建一个自定义注解,用于标记需要进行 json 格式验证的参数。
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = {JsonSyntaxValidator.class})
@Documented
public @interface MyValidator {
String message() default "{Token is not in Json syntax}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}接下来,我们需要创建一个校验器类,实现 ConstraintValidator 接口,并实现 isValid 方法,用于执行实际的 JSON 格式验证逻辑。
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class JsonSyntaxValidator implements ConstraintValidator<MyValidator, String> {
@Override
public void initialize(MyValidator constraintAnnotation) {
}
@Override
public boolean isValid(String token, ConstraintValidatorContext constraintValidatorContext) {
if (token == null || token.isEmpty()) {
return true; // Allow empty strings, or handle as needed
}
try {
JsonParser.parseString(token);
return true;
} catch (JsonSyntaxException e) {
return false;
}
}
}现在,我们可以在 Controller 中使用 @RequestBody 注解接收字符串请求体,并使用 @Valid 注解触发验证。需要注意的是,这里需要使用 @Valid 注解,而不是自定义的 @MyValidator 注解。 @MyValidator 只是定义了校验规则,而 @Valid 才是触发校验的注解。
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
public class MyController {
@RequestMapping(value = "/endpoint", method = {RequestMethod.POST})
@ResponseBody
public ResponseEntity<String> authorize(@Valid @RequestBody String token) {
// logic
return ResponseEntity.ok("Token is valid");
}
}注意事项:
总结:
通过以上步骤,我们成功地创建了一个自定义校验器,用于验证请求体中的字符串是否符合 JSON 格式。这种方法可以应用于各种需要自定义验证逻辑的场景,例如验证字符串是否符合特定的正则表达式,或者是否包含特定的字符。关键在于定义好自定义注解和校验器类,并在 Controller 中使用 @Valid 注解触发验证。
以上就是自定义校验器在 Spring Boot 中校验字符串请求体的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号