mkoryak
mkoryak

Reputation: 57918

spring mvc validation best practices

I am learning myself Spring MVC 2.5 mostly from the docs. Can someone explain the following:

Also, in this code how does the line ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); work? How can it check if the name is empty on the person object when the person object is not passed in?

   public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }

(this code is from section 5.2 from the docs)

Thanks

Upvotes: 4

Views: 3041

Answers (2)

Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

Here is the answer of your first question. http://chompingatbits.com/2009/08/25/spring-formtag-commandname-vs-modelattribute/

according to my experience there isn't easier way to fullfill validation, because it's easy enough. You can get it easier integrating libraries such as commons-validator into your project and use pre-defined validation rules in your forms.

http://numberformat.wordpress.com/tag/spring-mvc-validation/

and also with 3rd version of Spring you can use Bean validation using annotations.

Upvotes: 1

axtavt
axtavt

Reputation: 242686

  • The question about command object is not very clear. If you mean the following syntax

    @RequestMapping(...) public ModelAndView foo(Command c) { ... }
    

    then it is the same as the following

    @RequestMapping(...) public ModelAndView foo(@ModelAttribute Command c) { ... }
    

    because @ModelAttribute can be omitted. The only case when it's actually needed is then you need to specify attribute name explicitly (otherwise it would be inferred as a class name with the first letter decapitalized, i.e. command)

  • In Spring 2.5 - no. In Spring 3.0 you can use declarative validation with JSR-303 Bean Validation API.

  • The Errors object has a reference to the object being validated.

Upvotes: 3

Related Questions