[英]How to use annotation validator to Optional's inner value in java
I am using java 8, springboot 2.0.0 with spring-mvc. 我正在使用带有spring-mvc的java 8,springboot 2.0.0。 The code below doesn't check if the value wrapped by Optional is really email or not.
下面的代码不检查Optional包装的值是否真的是电子邮件。
import javax.validation.constraints.Email;
//...
@PostMapping("/foo")
public String foo(Optional<@Email String> email) {
// No exception is thrown even if email is not actually email format.
return "foo";
}
I heard of many validators works fine with Generic type, so this is embarrassing. 我听说许多验证器都可以与泛型类型配合使用,因此这很尴尬。
How can I make it work? 我该如何运作? Or, doesn't it provide the simple way?
还是不提供简单的方法?
I found that I omitted the @Validated
annotation on the controller. 我发现我在控制器上省略了
@Validated
注解。 With it, the method throws an javax.validation.ConstraintViolationException
if the parameter 'email' isn't actually email. 有了它,如果参数'email'实际上不是电子邮件,则该方法将引发
javax.validation.ConstraintViolationException
。
However, I wonder why explicit @Validated
is still needed. 但是,我想知道为什么仍然需要显式
@Validated
。 In my opinion, it might be more natural that @Validated
is just implicitly configured, and springboot provides the way to deactivate it in expectedly rare cases. 在我看来,
@Validated
只是隐式配置可能更为自然,而springboot提供了在极少数情况下将其停用的方法。
import javax.validation.constraints.Email;
//...
@Controller
@Validated // With this guy, now validation works well.
public class FooConroller {
@PostMapping("/foo")
public String foo(Optional<@Email String> email) {
//Now it works as expected.
return "foo";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.