Spring mvc verification recommendations

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

  • Advantages / Differences in Using command Objects Compared to Using @ModelAttribute to @ModelAttribute in an Object.
  • Is there an easier way to do validation and then write a Validator object?

Also, in this code, how does the line ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); ? How can he check if a person’s name is empty when the person’s object is not transferred?

  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 of the documents )

thanks

+4
source share
2 answers

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

according to my experience, there is no simpler way to authenticate because it is easy enough. You can simplify the integration of libraries, such as commons-validator, into your project, and use predefined validation rules in your forms.

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

as well as with the third version of Spring, you can use Bean validation with annotations.

+1
source
  • The issue of the command object is not very clear. If you mean the following syntax

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

    then this is the same as

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

    because @ModelAttribute can be omitted. The only case when this is really necessary is that you need to explicitly specify the attribute name (otherwise it would be displayed as a class name with the first decapitalization of the first letter, i.e. command )

  • In Spring 2.5, no. In Spring 3.0, you can use declarative validation using the JSR-303 Bean validation API.

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

+3
source

Source: https://habr.com/ru/post/1333813/


All Articles