自定义日期时间验证无法在Rest中工作

时间:2018-10-17 10:02:35

标签: java spring rest validation lombok

我创建了一个自定义的日期验证器,用于检查时间戳字符串,如下所示。该代码运行正常,但验证无效,并且响应正文中未显示任何消息。

当我发布如下所示的数据时

{
  "price": "0",
  "timestamp": "foo foo"
}

它给了我200。我的例外是获取有效的例外详细信息。有人可以帮我吗

StockController.java

@RestController
@AllArgsConstructor
@RequestMapping(value = "/stock", produces = MediaType.APPLICATION_JSON_VALUE)
public class StockController {

    @Autowired
    private StockService stockService;

    @PostMapping
    public void createStock(@Valid @RequestBody final Stock stock) {
        stockService.create(stock);
    }
}

DefaultControllerAdvice.java

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class DefaultControllerAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Exception handleException(Exception exception){
        return exception;
    }
}

Stock.java

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import com.challenge.validators.TimestampValidator;

import lombok.Data;

    @Data
    public class Stock {

        @Min(0)
        @NotNull
        public double price;

        @NotNull(message="Timestamp cannot be empty")
        @DateTimeValidator
        public String timestamp;
    }

DateTimeValidator.java

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = DateTimeValidatorCheck.class)
@Documented
public @interface DateTimeValidator {

    String message() default "Must be timestamp of format YYYY-MM-DDThh:mm:ss.sssZ";

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

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

DateTimeValidatorCheck.java

public class DateTimeValidatorCheck implements ConstraintValidator<DateTimeValidator, String> {

    @Override
    public void initialize(DateTimeValidator dateTimeValidator ) {
    }

    @Override
    public boolean isValid(String timestamp, ConstraintValidatorContext context) {
        if (timestamp == null) {
            return false;
        } else {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            try {
                LocalDate.parse(timestamp, dateTimeFormatter);
                return true;
            } catch (DateTimeParseException dateTimeParseException) {
                return false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的BindingResult bindingResult方法上需要一个createStock参数。使用它来检查验证错误:

if (bindingResult.hasErrors()) {
    // return error or throw exception
}