Spring portlet mvc: @Valid does not seem to work
Asked Answered
O

5

7

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.

Ornithic answered 26/11, 2010 at 8:27 Comment(0)
A
4

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
Amphitryon answered 26/11, 2010 at 8:34 Comment(16)
Thank you for the tip, I tried placing it in my userRegistration-portlet.xml but I get an: the prefix mvc for mvc:annotation-driven is not defined. But when I google <mvc:annotation-driven /> I don't see any differences?Ornithic
Edit: added: xmlns:mvc="springframework.org/schema/mvc" and I also added: springframework.org/schema/mvc/spring-mvc-3.0.xsd to my schemalocation. And now I get the error: the matching wildcard is strict, but no declaration can be found for the element mvc:annotation-driven. Sorry for the double post but my internet is really slow. So I might also miss some responses.Ornithic
I think I might be missing a maven dependencies, but I can't really think of one.Ornithic
@Jack - post your bean definition xml file.Transpose
@Bohzo, sadly that didn't change anything.Ornithic
I already get the error in my compiler (eclipse 3.6). Compiling and deploying it returns in the same message being delivered by a saxparseeception. So if I was only missing that missing line, I'm really thinking of a library problem. But I don't see any missing ones. And since I have quite a lot of dependencies also posting that will probably make the startpost too long.Ornithic
@Ornithic - you've put them in reverse order. the short one is above the xsd path.Amphitryon
Oh damn, never knew that one mattered... I feel really stupid now. Just wasted about an hour on that error.Ornithic
Getting one more error (hopefully the last): g.springframework.beans.factory.Bea nCreationException: Error creating bean with name 'org.springframework.validatio n.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLogger Binder However I do have have slf4j dependency:<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency>Ornithic
Update: added the log4j12 dependency and now I get another error. Now it deploys, but when I visit the page I get an: Error creating bean wit h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean# 0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.Configuratio nImpl in my consoleOrnithic
@Ornithic well, add Hibernate Validator to the classpath :) You need a JSR-303 providerAmphitryon
I have hibernate-validator 4.0.2.GA in my pom.xml. Which is why I'm so confused... Your e-mail is glamd@ etc right? I e-mailed you which might be easier than our slowchat.Ornithic
sorry, I'm not answering SO stuff on email ;)Amphitryon
Feel free to put the answer here, but I think we could find the answer sooner if we e-mailed a little bit (if you wouldn't mind). I'm just getting a bit frazzled because on first sight it should work but I'm getting NullPointerExceptions etc due to it.Ornithic
@Ornithic - look, I think I answered the question as it is. Now the fact that other problems arise is perhaps material for other questions.Amphitryon
You certainly have, I just wanted to keep this going since it already has most of the information. I just started a second thread: #4285893Ornithic
H
8

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

Hirschfeld answered 26/11, 2010 at 10:16 Comment(2)
I wish I found this post earlier. 99% of all the examples out there are missing this little bit of critical information.Muna
for an unknown reason, that solution did not work for me, but @Andy's did !Jo
A
4

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
Amphitryon answered 26/11, 2010 at 8:34 Comment(16)
Thank you for the tip, I tried placing it in my userRegistration-portlet.xml but I get an: the prefix mvc for mvc:annotation-driven is not defined. But when I google <mvc:annotation-driven /> I don't see any differences?Ornithic
Edit: added: xmlns:mvc="springframework.org/schema/mvc" and I also added: springframework.org/schema/mvc/spring-mvc-3.0.xsd to my schemalocation. And now I get the error: the matching wildcard is strict, but no declaration can be found for the element mvc:annotation-driven. Sorry for the double post but my internet is really slow. So I might also miss some responses.Ornithic
I think I might be missing a maven dependencies, but I can't really think of one.Ornithic
@Jack - post your bean definition xml file.Transpose
@Bohzo, sadly that didn't change anything.Ornithic
I already get the error in my compiler (eclipse 3.6). Compiling and deploying it returns in the same message being delivered by a saxparseeception. So if I was only missing that missing line, I'm really thinking of a library problem. But I don't see any missing ones. And since I have quite a lot of dependencies also posting that will probably make the startpost too long.Ornithic
@Ornithic - you've put them in reverse order. the short one is above the xsd path.Amphitryon
Oh damn, never knew that one mattered... I feel really stupid now. Just wasted about an hour on that error.Ornithic
Getting one more error (hopefully the last): g.springframework.beans.factory.Bea nCreationException: Error creating bean with name 'org.springframework.validatio n.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLogger Binder However I do have have slf4j dependency:<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency>Ornithic
Update: added the log4j12 dependency and now I get another error. Now it deploys, but when I visit the page I get an: Error creating bean wit h name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean# 0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.Configuratio nImpl in my consoleOrnithic
@Ornithic well, add Hibernate Validator to the classpath :) You need a JSR-303 providerAmphitryon
I have hibernate-validator 4.0.2.GA in my pom.xml. Which is why I'm so confused... Your e-mail is glamd@ etc right? I e-mailed you which might be easier than our slowchat.Ornithic
sorry, I'm not answering SO stuff on email ;)Amphitryon
Feel free to put the answer here, but I think we could find the answer sooner if we e-mailed a little bit (if you wouldn't mind). I'm just getting a bit frazzled because on first sight it should work but I'm getting NullPointerExceptions etc due to it.Ornithic
@Ornithic - look, I think I answered the question as it is. Now the fact that other problems arise is perhaps material for other questions.Amphitryon
You certainly have, I just wanted to keep this going since it already has most of the information. I just started a second thread: #4285893Ornithic
N
2

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); }

Nog answered 29/12, 2014 at 21:45 Comment(0)
B
0

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.

Belloc answered 26/11, 2010 at 9:24 Comment(1)
That's quite a bit more verbose than the mvc:annotation-drive route but thank you for your input.Ornithic
F
0

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>
Fumarole answered 22/9, 2022 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.