網頁

2020/5/5

Spring Boot 自訂Java Bean Validation驗證參數是否為Hex文字格式

Java Bean Validation驗證Spring Boot Controller請求物件屬性是否為Hex表示格式(僅接受數字0-9,英文字母A-F)。

專案要用Maven或Gradle匯入org.springframework.boot:spring-boot-starter-validation的依賴。


建立Validator類別HexValidator,繼承ConstraintValidator並實作isValid()方法,此方法中判斷請求物件的屬性格式是否為hex格式。此類別用在@HexValidation的驗證器。

HexValidator

package com.abc.demo.validator;

import com.abc.demo.validation.HexValidation;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

public class HexValidator implements ConstraintValidator<HexValidation, String> {

    private static final Pattern HEX_PATTERN = Pattern.compile("^[0-9a-fA-F]+$");

    @Override
    public void initialize(HexValidation constraintAnnotation) {}
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)) {
            return false;
        }
        return HEX_PATTERN.matcher(value.toUpperCase()).matches();
    }

}

建立標注用的annotation @HexValidation,放在要被驗證格式的屬性上。加上@Constraint(validatedBy = HexValidator.class)指定HexValidator為驗證器。

@HexValidation

package com.abc.demo.validation;

import com.abc.demo.validator.HexValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Constraint(validatedBy = HexValidator.class)
@Target({METHOD, FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface HexValidation {

    String message() default "Only accept hex text(0-9,a-f)"; // 若驗證失敗會丟出的錯誤訊息。

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}


送進Controller的請求物件DemoRequestDto,在屬性text上套用@HexValidation,當物件傳入Controller的方法中該屬性就會經由@HexValidationHexValidator驗證。

DemoRequestDto

package com.abc.demo.controller.request;

import com.abc.demo.validation.HexValidation;

public class DemoRequestDto {

    @HexValidation
    private String text;

    public void setText(String text) { this.text = text; }
    public String getText() { return this.text; }

}

傳入物件的參數前需加上@Valid才會發生驗證,否則驗證會被忽略。

DemoController

package com.abc.demo.controller;

import com.abc.demo.controller.request.DemoRequestDto
import com.abc.demo.controller.response.DemoResponse;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/text")
public class DemoController {

    @PostMapping("/add")
    public DemoResponse add(@RequestBody @Valid DemoRequestDto demoRequestDto) {
        ...
    }
}

沒有留言:

張貼留言