String上的Spring MVC方法中的Hibernate验证器

时间:2015-03-30 13:58:30

标签: java spring-mvc hibernate-validator

我有一个控制器方法,它以String作为参数 我想使用hibernate验证器验证输入,但我真的不想为此创建一个对象。

有什么方法可以在字符串上使用hibernate验证器吗? 如果没有,请随意提出替代方法。

2 个答案:

答案 0 :(得分:1)

您可以在applicationcontext中使用此配置

<bean id="validatorFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" />

<bean id="validator" factory-bean="validatorFactory" factory-method="getValidator" />

然后在服务或组件中注入此验证器,如下所示。

/**
 * 
 */
@Component
public class ValidationService {

    @Autowired
    private Validator validator;

    /**
     * Check the Set and return the errors that it contains.
     * 
     * @param errors
     * @return Errors found
     * @since Jan 15, 2014
     */
    public String returnErrors(final Set<ConstraintViolation<Object>> errors) {
        final StringBuilder builder = new StringBuilder();
        for (final ConstraintViolation<Object> error : errors) {
            builder.append(error.getMessage());
        }
        return builder.toString();
    }

    /**
     * Validate entities using JSR 303
     * 
     * @param object
     * 
     * @param classes
     * @throws IllegalArgumentException
     * @since Jan 15, 2014
     */
    public void validateEntity(final Object object, final Class<? extends Default>... classes) {
        final Set<ConstraintViolation<Object>> errors = validator.validate(object, classes);
        if (!errors.isEmpty()) {
            throw new IllegalArgumentException(returnErrors(errors));
        }
    }

}

之后,您可以在所需的每个类中使用注入服务并使用它。

validationService.validateEntity(salesForceForm, PriceChangeRequestGroup.class);

答案 1 :(得分:0)

请在使用hibernate验证器的简单Java应用程序中找到下面的代码。

package testjarcopy;

import java.lang.reflect.Method;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.executable.ExecutableValidator;

public class TestCopy {

    public static void main(String[] args) throws NoSuchMethodException,
            SecurityException {

        TestCopy object = new TestCopy();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

        Method method = TestCopy.class.getMethod("placeOrder", String.class, int.class);
        Object[] parameterValues = { "12", 6 };
        ExecutableValidator executableValidator = factory.getValidator().forExecutables();

        Set<ConstraintViolation<TestCopy>> violations = executableValidator.validateParameters(object, method, parameterValues);

        System.out.println("violations.size=" + violations.size());
    }

    public void placeOrder(
            @NotNull @Size(min = 3, max = 5) String customerCode,
            @Min(6) int quantity) {
        System.out.println("running in method..." + customerCode);

    }

}

以下是您需要添加的依赖项。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.4</version>
</dependency>

希望这有帮助。