我在模型类中声明了这个字段:
@Size(min = 2, max = 200, message = "{validation.name.size}")
private String name;
Run Code Online (Sandbox Code Playgroud)
其中validation.name.size是本地化消息的路径。问题是我不想输出诸如“名称太长或太短”之类的消息。
有没有办法使用两个不同的消息并检查最小和最大字符串长度?@Min并且@Max仅适用于数字类型,因此不能使用它们。字符串的替代品是什么?
我一直在尝试将弹簧验证器添加到spring-data-rest项目中.
我跟着并通过以下链接设置"入门"应用程序:http://spring.io/guides/gs/accessing-data-rest/
...现在我正在尝试通过以下文档添加自定义PeopleValidator:http://docs.spring.io/spring-data/rest/docs/2.1.0.RELEASE/reference/html/validation-chapter html的
我的自定义PeopleValidator看起来像
package hello;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class PeopleValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public void validate(Object target, Errors errors) {
errors.reject("DIE");
}
}
Run Code Online (Sandbox Code Playgroud)
...而我的Application.java类现在看起来像这样
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public PeopleValidator beforeCreatePeopleValidator() …Run Code Online (Sandbox Code Playgroud) 我在一些字段上有一个带有hibernate验证注释的类(例如@NotNull和@Size(min = 4, max = 50)等...)
public class MyClass {
Long id;
@NotEmpty
@Size(min = 4, max = 50)
String machineName;
@NotEmpty
@Size(min = 4, max = 50)
String humanName;
// Getters, setters, etc…
}
Run Code Online (Sandbox Code Playgroud)
我还有一个充当JSON API的自定义控制器,以及一个在调用API方法时创建MyClass对象的JSON反序列化器.在我的自定义控制器中,我有一个方法来创建该类型的新对象:
@RequestMapping(method = RequestMethod.POST)
public long createMyObject(@RequestBody @Valid MyClass newObj) {
// Create the object in the database
return newObj.getId();
}
Run Code Online (Sandbox Code Playgroud)
和另一种更新现有对象的方法
@RequestMapping(method = RequestMethod.PUT)
public void updateMyObject(@RequestBody MyClass updatedObj) {
MyClass existingObj = // Get existing obj from DB …Run Code Online (Sandbox Code Playgroud) 我有以下简单的项目来测试 Spring Boot 验证。我使用的是 Spring boot 版本 2.5.6
pom.xml 中的验证依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
DTO对象
import javax.validation.constraints.NotNull;
public class DepartmentDTO {
@NotNull(message = "Department name can not be empty")
private String name;
// getter and setter
}
Run Code Online (Sandbox Code Playgroud)
休息控制器
@RestController
public class DepartmentResource {
@PostMapping("/departments")
public ResponseEntity<DepartmentDTO> createDepartment(@Valid @RequestBody DepartmentDTO department) {
return new ResponseEntity<>(department, HttpStatus.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
当我触发具有空名称的请求时,我收到错误响应,但消息丢失:
{
"timestamp": "2021-12-03T09:13:52.729+00:00",
"status": 400,
"error": "Bad Request",
"path": "/departments"
}
Run Code Online (Sandbox Code Playgroud) 我在看@org.hibernate.validator.constaints.NotEmpty注释:
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
/**
* Defines several {@code @NotEmpty} annotations on the same element.
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface List {
NotEmpty[] value();
}
}
Run Code Online (Sandbox Code Playgroud)
我对最后一部分感到困惑:
/**
* Defines several {@code @NotEmpty} annotations on the …Run Code Online (Sandbox Code Playgroud) 我有一个包含字符串列表的模型类.列表可以为空或包含元素.如果它有元素,那么这些元素不能为空.举个例子,假设我有一个叫做QuestionPaper的类,它有一个questionIds列表,每个都是一个字符串.
class QuestionPaper{
private List<String> questionIds;
....
}
Run Code Online (Sandbox Code Playgroud)
论文可以有零个或多个问题.但如果有问题,则id值不能为空字符串.我正在使用SpringBoot,Hibernate,JPA和Java编写一个微服务.我该怎么做这个验证.任何帮助表示赞赏.
举个例子,我们需要拒绝来自用户的以下json输入.
{ "examId": 1, "questionIds": [ "", " ", "10103" ] }
Run Code Online (Sandbox Code Playgroud)
是否有任何开箱即用的方法来实现这一目标,或者我是否必须为此编写自定义验证器.
我有一个从第三方浏览器重定向回我的 Spring 控制器收到的地图,如下所示 -
@RequestMapping(value = "/capture", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public void capture(@RequestParam
final Map<String, String> response)
{
// TODO : perform validations first.
captureResponse(response);
}
Run Code Online (Sandbox Code Playgroud)
在使用此有效负载之前,我需要进行重要的验证,包括首先检查映射的非空值,然后在校验和验证中使用这些值。因此,我想使用 Spring Validator 接口以编程方式验证我的有效负载。但是,我找不到任何用于验证映射的验证器示例。
为了验证 Java 对象,我了解如何通过传递对象和 BeanPropertyBindingResult 以包含验证器的错误来调用验证器,如下所示 -
final Errors errors = new BeanPropertyBindingResult(object, objectName);
myValidator.validate(object, errors);
if (errors.hasErrors())
{
throw new MyWebserviceValidationException(errors);
}
Run Code Online (Sandbox Code Playgroud)
对于 Map,我可以看到有一个MapBindingResult扩展的类AbstractBindingResult。我应该简单地使用它,并将我的地图传递Object object给验证器并将其转换回 aMap吗?另外,验证器方法如何supports(final Class<?> clazz)在我的验证器中实现?是否就像下面的代码片段一样,只能有一个验证器支持 HashMap 的这一通用类?总感觉不太对劲。(虽然这对我来说并不重要,因为我将注入验证器并直接使用它,而不是通过验证器注册表,但仍然很好奇。)
@Override
public boolean supports(final Class<?> clazz)
{ …Run Code Online (Sandbox Code Playgroud) 我创建了一个小示例项目,以显示我在Spring Boot验证配置及其与Hibernate集成时遇到的两个问题.我已经尝试过我发现的有关该主题的其他回复,但遗憾的是它们对我不起作用或者要求禁用Hibernate验证.
我想使用自定义的Validator实现ConstraintValidator<ValidUser, User>并注入我的UserRepository.同时我想保持Hibernate的默认行为,在更新/持久化期间检查验证错误.
我在这里写的是应用程序的完整主要部分.
自定义配置
在这个类中,我使用自定义设置自定义验证器MessageSource,因此Spring将从文件中读取消息resources/messages.properties
@Configuration
public class CustomConfiguration {
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:/messages");
messageSource.setUseCodeAsDefaultMessage(false);
messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
messageSource.setFallbackToSystemLocale(false);
return messageSource;
}
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(messageSource());
return factoryBean;
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
}
Run Code Online (Sandbox Code Playgroud)
如果不是自定义验证器,那么bean没什么特别之处@ValidUser
@ValidUser
@Entity
public class User extends AbstractPersistable<Long> {
private static …Run Code Online (Sandbox Code Playgroud) 我在Spring项目中一直使用Hibernate Validator.我即将JUser自动验证我的对象.即,我希望Spring验证对象并在BindigResult中设置错误.但它不起作用.
<properties>
<spring.version>4.3.5.RELEASE</spring.version>
<spring.security.version>4.0.2.RELEASE</spring.security.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<validation-api.version>1.1.0.Final</validation-api.version>
<hibernate-validator.version>5.4.0.Final</hibernate-validator.version>
</properties>
....
Run Code Online (Sandbox Code Playgroud)
...
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<context:annotation-config />
<context:component-scan base-package="my.project.controller" />
<mvc:annotation-driven validator="validator">
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
<property name="validator" ref="validator"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
Run Code Online (Sandbox Code Playgroud)
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class JUser implements Officeable {
@Id
private Long id;
@Column(unique = true, nullable = false)
private String username;
private …Run Code Online (Sandbox Code Playgroud) validation spring spring-mvc hibernate-validator spring-validator
我们能够使用 openApi 文档并使用 spring swagger-codegen 生成 Java 输入类。此外,我们可以在为常见约束(如长度、强制等)生成输入时注入 javax.validation 注释。
我希望将其提升到下一个自定义级别,并能够使用与 Spring 的 @Constraint 注释连接的自定义验证注释来注释生成的输入类。这样我们就可以为我们的项目重用特定的验证。
我希望有一个开箱即用的解决方案。您使用自定义验证注释生成输入类的首选方法是什么?
java spring-validator swagger-2.0 swagger-codegen swagger-codegen-maven-plugin
spring-validator ×10
java ×8
spring ×7
validation ×5
hibernate ×2
spring-boot ×2
annotations ×1
java-8 ×1
rest ×1
spring-mvc ×1
string ×1
swagger-2.0 ×1