我刚刚用Hibernate实现了Bean Validation.
如果我显式调用验证器它按预期工作,并且按预期注入连接到DB的@Autowired DAO bean.
我以前发现我需要在上面的内容之前添加以下语句.之前我已经广泛使用了@Autowired bean,但下面的语句对于由Spring管理验证器和注入ConstraintValidator的bean是必要的.
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
Run Code Online (Sandbox Code Playgroud)
但是,当在SessionFactory.getCurrentSession.merge期间自动调用验证器时,bean为null.
如果我通过调用javax.Validation.validate直接调用验证器,它的工作原理使我认为我已正确设置了Spring配置.
我已经读过人们无法获得DAO bean @Autowired的帖子的数字,但在我的情况下,除了在合并期间调用时.
下面的日志输出显示首先直接调用验证器,然后作为合并操作的结果调用.
07.12.2011 01:58:13 INFO [http-8080-1] (FileTypeAndClassValidator:isValid) - Validating ...
07.12.2011 01:58:13 INFO [http-8080-1] (ConstraintValidatorHelper:getPropertyValue) - propertyName=className, returnValue=com.twoh.dto.PurchaseOrder
07.12.2011 01:58:13 INFO [http-8080-1] (ConstraintValidatorHelper:getPropertyValue) - propertyName=fileTypeId, returnValue=4
07.12.2011 01:58:13 INFO [http-8080-1] (QueryUtil:createHQLQuery) - select ft.id from FileType ft where ft.id = :fileTypeId and ft.fileClassName = :fileClassName
07.12.2011 01:58:13 INFO [http-8080-1] (BaseDAO:merge) - Entity: com.twoh.dto.PurchaseOrder: 1036.
07.12.2011 01:58:13 INFO [http-8080-1] (FileTypeAndClassValidator:isValid) - Validating ...
07.12.2011 01:58:13 INFO …Run Code Online (Sandbox Code Playgroud) 我使用spring 3.0.2来开发一个像twitter这样简单的基于Web的应用程序.我的服务器端验证在JSR验证API方面表现良好,但在验证失败时,我无法找到任何在JSR验证API中国际化消息的方法.
我在我的模型类Spitter.java上使用以下注释来表示应用程序中的用户.
公共类Spitter实现Serializable {
Run Code Online (Sandbox Code Playgroud)private Long id; @Size(min=8, max=15, message="some msg..") @Pattern(regexp="^[a-zA-Z0-9]+$", message="some msg..") private String username; @Size(min=8, max=15, message="some msg..") private String password; @Size(min=3, max=15, message="some msg..") private String name; @Pattern(regexp="^$",message="some msg..") private String email; @NotNull(message="some msg..") @NumberFormat(style= NumberFormat.Style.NUMBER) @Min(value=14, message="some msg..") @Max(value=99, message="some msg..") private Integer age; //getter setter not shown }
我已经检查了JSR Validation API,以便在验证失败时获得本地化支持,但无法找到相同的内容.
有什么方法可以实现国际化.
提前致谢...
假设我在这样的字段上进行验证:
@NotEmpty
@Digits(integer = 3, fraction = 0)
private String code;
Run Code Online (Sandbox Code Playgroud)
目前,如果我将表单字段留空,我会使用Spring MVC和Hibernate验证.有没有办法只显示@NotEmpty消息?
我们在Spring MVC中使用@ Min,@ Max,@ NotNull等注释进行服务器端验证.这些注释应该放在Model Class中.我希望在需要时应用这样的注释,我不想在Model类中应用这样的注释.
例如.
我有一个具有属性名称,性别,电子邮件的人员.如果我将@NotNull注释放在电子邮件属性上,那么它将获得全局应用,如果我的要求发生变化,就好像在我的系统中有两个人学生和教师和教师注册电子邮件是可选的但是对于学生它不是null那么我怎么能得到这个.
在上述例子的情况下,我可以动态地应用验证注释 -
如果UserRegistration是For Teacher,那么Email是可选的.
如果UserRegistration是For Student,则电子邮件是强制性的.
@Pattern还是使用其他方法?@Pattern要走的路是什么regex?@Pattern在同一字段的两个不同组中使用两个 注释吗?我想以下列方式自定义我的错误消息:
假设以下类Person的声明:
@Size(min=10, max=200, message="{name.size}")
private String name;
Run Code Online (Sandbox Code Playgroud)
在ValidationMessages.properties中声明的错误消息中,我想输出字段值,即我想做这样的事情:
name.size=The name '{name}' is invalid, its size must be between {min} and {max}
Run Code Online (Sandbox Code Playgroud)
假设字段'name'的内容是"abc".然后错误消息应如下所示:
名称"abc"无效,其大小必须介于10到200之间
min和max的替换有效,但我怎样才能为字段值执行此操作?
我正在考虑使用布尔逻辑与我的bean验证使用Hibernate验证器在AND约束不足的情况下.我发现可以通过使用文档中描述的@ConstraintComposition注释创建新注释来更改此默认行为.该文档提供了以下示例.
@ConstraintComposition(OR)
@Pattern(regexp = "[a-z]")
@Size(min = 2, max = 3)
@ReportAsSingleViolation
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface PatternOrSize {
String message() default "{org.hibernate.validator.referenceguide.chapter11." +
"booleancomposition.PatternOrSize.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Run Code Online (Sandbox Code Playgroud)
使用这种@PatternOrSize验证约束意味着输入字符串或者小写或具有2和3之间的尺寸现在,这引发了几个问题:
AND和OR同时?我找不到任何暗示这是可能的东西,但也许我错过了一些东西.@Pattern和@Size约束动态化?因为否则我想我必须为我需要的每个参数组合定义一个新的注释.仅仅为了更改参数而定义一个新的注释@Size似乎不可行,但可能是必要的?先感谢您.
我有一个带有web方法的控制器,如下所示:
public Response registerDevice(
@Valid final Device device,
@RequestBody final Tokens tokens
) {...}
Run Code Online (Sandbox Code Playgroud)
一个看起来像这样的验证器:
public class DeviceValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Device.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
// Do magic
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图让Spring验证由拦截器生成的Device参数.但每次我尝试时,它都会验证令牌参数.
我已经尝试使用@InitBinder指定验证器,@Validated而不是@Valid注册MethodValidationPostProcessor类.到目前为止没有运气.
根本不调用验证器,或者在验证Device参数时验证tokens参数.
我正在使用Spring 4.1.6和Hibernate验证器5.1.3.
谁能提供任何关于我做错的线索?我整个下午都在网上试图解决这个问题.不敢相信春天的验证区域仍然像5年前一样混乱:-(
注释如下:
@Pattern(regexp = "^[0-9]+$")
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTestAnnotation {
}
Run Code Online (Sandbox Code Playgroud)
当我用@MyTestAnnotion注释一个字段时,即使该字段不包含所有数字,该呼叫也会顺利进行。
以下部分已由以下给出的答案解决。主要问题仍然存在。我尝试添加:
@Pattern(regexp = "^[0-9]+$")
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
public @interface MyTestAnnotation {
}
Run Code Online (Sandbox Code Playgroud)
在我的@MyTestAnnotation上,它不会让我输入message属性,但是当我运行代码时,它给出了错误,指出未指定message属性。
如果我将@Pattern批注直接放在字段上,则其行为将符合预期。
我在这里想念什么吗?
我正在将Spring Boot 1.3.5与Rest Controllers一起使用,并且一切正常。
我还在官方文档中使用了Spring的验证示例技术(JSR-303 Bean验证API和Spring的验证器接口,我都尝试过并且遇到相同的问题),并且验证有效,但是我无法配置自定义消息。
我已经配置了messages.properties文件,并且可以很好地访问此文件上的消息。但是,此验证似乎无法读取或访问通过Spring Boot自动配置的我的消息源(messages.properties)。
我可以直接通过@Autowired从控制器中注入的消息源对象访问消息(代码中有注释)。但是,Spring的验证器接口或JSR-303 Bean验证的绑定结果似乎无法访问MessageSource中加载的messages.properties。我得到的结果是我的错误有代码,但没有默认消息。
这是我的应用程序类:
@SpringBootApplication
@ImportResource({ "classpath:security/cas-context.xml", "classpath:security/cas-integration.xml",
"classpath:security/security.xml" })
@EnableAutoConfiguration(exclude = VelocityAutoConfiguration.class) // http://stackoverflow.com/questions/32067759/spring-boot-starter-cache-velocity-is-missing
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ServletRegistrationBean cxfServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public Nfse nfseService() {
return new NfseImpl();
}
@Bean
public Endpoint …Run Code Online (Sandbox Code Playgroud) bean-validation ×10
java ×5
spring ×3
spring-mvc ×3
annotations ×1
autowired ×1
field ×1
hibernate ×1
javabeans ×1
jsr ×1
regex ×1
spring-boot ×1
substitution ×1
validation ×1