自定义校验器在 Spring Boot 中校验字符串请求体

在 Spring Boot 应用中,我们经常需要对请求体进行校验,以确保接收到的数据符合预期的格式和规范。对于简单的字符串请求体,我们可以通过自定义校验器来实现更灵活的验证逻辑。本文将介绍如何创建一个自定义校验器,用于验证请求体中的字符串是否符合 JSON 格式。

首先,我们需要创建一个自定义注解,用于标记需要进行 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[] payload() default {};

}

接下来,我们需要创建一个校验器类,实现 ConstraintValidator 接口,并实现 isValid 方法,用于执行实际的 JSON 格式验证逻辑。

import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import ja

vax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class JsonSyntaxValidator implements ConstraintValidator { @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 authorize(@Valid @RequestBody String token) {
        // logic
        return ResponseEntity.ok("Token is valid");
    }
}

注意事项:

  • 确保你的 Spring Boot 项目引入了 javax.validation 依赖,通常是通过 spring-boot-starter-validation 依赖引入。
  • @Valid 注解必须与 @RequestBody 一起使用才能触发验证。
  • 如果验证失败,Spring Boot 会抛出 MethodArgumentNotValidException 异常,你需要全局异常处理来捕获并处理该异常,返回合适的错误信息。

总结:

通过以上步骤,我们成功地创建了一个自定义校验器,用于验证请求体中的字符串是否符合 JSON 格式。这种方法可以应用于各种需要自定义验证逻辑的场景,例如验证字符串是否符合特定的正则表达式,或者是否包含特定的字符。关键在于定义好自定义注解和校验器类,并在 Controller 中使用 @Valid 注解触发验证。