Spring portlet mvc:@Valid 似乎不起作用

发布于 2024-10-04 08:11:38 字数 3270 浏览 12 评论 0原文

我创建了一个 bean 类并在我的控制器中使用它,但它似乎不起作用。 也就是说,即使我输入了无效的年龄,result.hasErrors 仍然是 false。

Bean 类:

public class User{
    @Min(13)
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName(){
            return name;
    }

    public void setName(String name){
            this.name = name;
    }   
}

控制器片段:

@ActionMapping(params = "myAction=validateUser")
    public void validateUser(ActionRequest request, ActionResponse response, ModelMap model, @ModelAttribute("user") @Valid User user, BindingResult result ){      

        if(result.hasErrors()){
            for(ObjectError oe : result.getAllErrors()){
                System.out.println(oe.getDefaultMessage());
            }
        } else{
            //code
        }
    }

JSP:

<form:form action="${registerUser}" method="post" commandName="user">
    <b>User</b> 
    <form:input path="age"/>
    <form:input path="name"/>
    <input type="submit" value="register"/>
</form:form>

编辑: 我的 userRegistration-portlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/mvc
        ">

    <mvc:annotation-driven /> 

    <import resource="spring-hibernate.xml"/>

    <context:component-scan base-package="comjohndoe.dao" />
    <context:component-scan base-package="comjohndoe.model" />
    <context:component-scan base-package="comjohndoe.service" />
    <context:component-scan base-package="comjohndoe.util" />
    <context:component-scan base-package="comjohndoecontroller" />

    <bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

mvc:spring-validation 行给了我: cvc-complex-type.2.4.c 匹配的通配符是严格的,但找不到元素 mvc 的声明:注释驱动。 错误。

I created a bean class and use it in my controller but it does not seem to work.
Namely even though I enter an invalid age, result.hasErrors is still false.

Bean class:

public class User{
    @Min(13)
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName(){
            return name;
    }

    public void setName(String name){
            this.name = name;
    }   
}

Controller snippet:

@ActionMapping(params = "myAction=validateUser")
    public void validateUser(ActionRequest request, ActionResponse response, ModelMap model, @ModelAttribute("user") @Valid User user, BindingResult result ){      

        if(result.hasErrors()){
            for(ObjectError oe : result.getAllErrors()){
                System.out.println(oe.getDefaultMessage());
            }
        } else{
            //code
        }
    }

JSP:

<form:form action="${registerUser}" method="post" commandName="user">
    <b>User</b> 
    <form:input path="age"/>
    <form:input path="name"/>
    <input type="submit" value="register"/>
</form:form>

edit:
My userRegistration-portlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/mvc
        ">

    <mvc:annotation-driven /> 

    <import resource="spring-hibernate.xml"/>

    <context:component-scan base-package="comjohndoe.dao" />
    <context:component-scan base-package="comjohndoe.model" />
    <context:component-scan base-package="comjohndoe.service" />
    <context:component-scan base-package="comjohndoe.util" />
    <context:component-scan base-package="comjohndoecontroller" />

    <bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

It's the mvc:spring-validation line that is giving me the: cvc-complex-type.2.4.c the matching wildcard is strict, but no declaration can be found for the element mvc:annotation-driven. error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

蹲墙角沉默 2024-10-11 08:11:38

我有完全相同的问题。我阅读了 https://jira.springframework.org/browse/SPR-6817 并工作通过添加到我的配置来解决问题:

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator">
                <ref bean="validator"/>
            </property>
        </bean>
    </property>
</bean>

您的项目中还需要有一个 JSR-303 验证器才能使其可用 为此,我使用了 Hibernate 验证器:http://www.hibernate.org/subprojects/validator.html

I had exactly the same problem. I read https://jira.springframework.org/browse/SPR-6817 and worked the problem around by adding to my config:

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="validator">
                <ref bean="validator"/>
            </property>
        </bean>
    </property>
</bean>

You also need to have a JSR-303 validator in your project in order for it to be available For this I used Hibernate Validator: http://www.hibernate.org/subprojects/validator.html

嘴硬脾气大 2024-10-11 08:11:38

您需要 来启用 jsr-303 验证。如果您出于某种原因不想使用它,或者在某些时候它开始产生问题(就像对我一样),请查看 这个问题

更新:
schemaLocation 中,mvc 条目应包含以下两个

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

You need <mvc:annotation-driven /> to enable jsr-303 validation. If you don't want to use it for some reason, or if at some point it starts creating problems (like it did for me), take a look at this question

Update:
in schemaLocation the mvc entry should contain these two:

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
年华零落成诗 2024-10-11 08:11:38

您需要执行以下操作,这就是我在 spring portlet mvc 项目中解决的方法。

  1. mvc:annotation-driven 添加到您的 applicatonContext.xml

  2. 添加以下代码在你的控制器中:

    <代码>@Autowired
    私有 LocalValidatorFactoryBean 验证器;

    <代码>@InitBinder
    公共无效initBinder(WebDataBinder活页夹){
    binder.setValidator(验证器);
    }

You need to do the following, that is how I solved in the spring portlet mvc project.

  1. Add mvc:annotation-driven to your applicatonContext.xml

  2. Add the following code in your controller:

    @Autowired
    private LocalValidatorFactoryBean validator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
    }

诗笺 2024-10-11 08:11:38

我认为原因是 ServletRequestDataBinder (扩展 DataBinder)没有 org.springframework.validation.Validator 实例,因此它不会验证任何内容(验证 @Valid 注解的 bean必须有 javax.validation.Validator 实例)。

org.springframework.validation.DataBinder

    public void validate() {
            Validator validator = getValidator();
            if (validator != null) {
                validator.validate(getTarget(), getBindingResult());
            }
        }

您可以在 @InitBinder 注解的方法中设置 Validator 实例:-

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new MyValidator());
    }

您还可以在 WebBindingInitializer

StandardBindingInitializer

   public class StandardBindingInitializer implements WebBindingInitializer {
        @Autowired
        private LocalValidatorFactoryBean validator;
        public void setValidatorFactory(LocalValidatorFactoryBean validator) {
            this.validator = validator;
        }

        @Override
        public void initBinder(WebDataBinder binder, WebRequest request) {
            binder.setValidator(validator);
    }
}

要创建 LocalValidatorFactoryBean 的实例,请使用 mvc:annotation-driven将 LocalValidatorFactoryBean 设置为 bean

I think the reason is that ServletRequestDataBinder (extends DataBinder) has no org.springframework.validation.Validator instance, so it does not validate anything (to validate @Valid annotated bean you must have javax.validation.Validator instance).

org.springframework.validation.DataBinder

    public void validate() {
            Validator validator = getValidator();
            if (validator != null) {
                validator.validate(getTarget(), getBindingResult());
            }
        }

You can set the Validator instance in @InitBinder annotated methods:-

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new MyValidator());
    }

Yo can also set the validator instance in WebBindingInitializer.

StandardBindingInitializer

   public class StandardBindingInitializer implements WebBindingInitializer {
        @Autowired
        private LocalValidatorFactoryBean validator;
        public void setValidatorFactory(LocalValidatorFactoryBean validator) {
            this.validator = validator;
        }

        @Override
        public void initBinder(WebDataBinder binder, WebRequest request) {
            binder.setValidator(validator);
    }
}

To create an instance of LocalValidatorFactoryBean either use mvc:annotation-driven OR set up LocalValidatorFactoryBean as bean.

双手揣兜 2024-10-11 08:11:38

使用 hibernate-validator jar 6.2 及以下版本,因此它可以支持 spring 5 及以上版本...

在 pom.xml 中添加依赖项:

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.2.Final</version>
</dependency>

Use hibernate-validator jar 6.2 version and below and so it can support spring 5 and above versions...

Add dependency in pom.xml:

<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.2.Final</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文