本文介绍了Spring注解@ModelAttribute和@Valid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用@ModelAttribute@Valid有什么优势?

有哪些区别?

是否可以同时使用它们?

Is it possible to use them together?

推荐答案

@ModelAttribute用于将方法参数或方法返回类型映射/绑定到命名模型属性.参见 @ModelAttribute s JavaDoc.这是一个Spring注释.

@ModelAttribute is used to map/bind a a method parameter or method return type to a named model attribute. See @ModelAttributes JavaDoc. This is a Spring annotation.

@Valid是一个注释,用于标记用于 JSR-303 bean验证的对象.请参见 @有效的JavaDoc.它是JavaEE 6的一部分,但我认为Hibernate具有较早的实现,大多数人都使用它来实现.

@Valid is an annotation that marks an object for JSR-303 bean validation. See @Valids JavaDoc. It is part of JavaEE 6, but I think Hibernate has an earlier implementation that most people use instead.

使用@ModelAttribute的优点是您可以将表单的输入映射到Bean. @Valid的优点在于,您可以利用JSR-303 Bean验证来确保针对某些规则对制成的Bean进行了验证.

The advantage of using @ModelAttribute is that you can map a form's inputs to a bean. The advantage of @Valid is that you can utilize JSR-303 bean validation to ensure that the bean that is made is validated against some set of rules.

是的,您可以同时使用@ModelAttribute@Valid.

Yes you can use @ModelAttribute and @Valid together.

将数据从表单(sic View)传输到Model对象的最佳方法是使用Spring遵循典型/传统的MVC设计模式.我个人更喜欢的方法是在JSP中使用带有Spring JSTL <form:*>标记并设置了modelAttribute的表单.在Controller上,具有一个处理程序以接受具有匹配的@ModelAttribute的表单的POST,该@ModelAttribute是表示表单输入的Bean.然后,我会将"Form Bean"传递给服务层以执行某些操作,包括在需要时将"Form Bean"转换为任何模型(如果表单直接创建模型对象,则无需这样做),并通过以下方式保存/更新/等:一个DAO.这只是做事的一种方式,但这可能是我在日常工作中对Spring所做的大部分工作.

The best way to transfer data from a form (sic View) to the a Model object is to follow the typical/traditional MVC design pattern using Spring. My personal preferred way is to have a form in a JSP with Spring JSTL <form:*> tags, with a modelAttribute set. On the Controller, have a handler to accept the POST from the form that has a matching @ModelAttribute that is a bean that represents the form's input. I would then pass that "Form Bean" to a service layer to do some things, including translating the "Form Bean" into any models if needed (not necessary if the form is creating your model objects directly) and saving/updating/etc via a DAO. This is but one way to do things, but it's probably the bulk of what I do with Spring in my day-to-day job.

我会高度建议阅读Spring参考资料并按照教程进行操作.这些参考资料写得很好,易于阅读,并且包含许多示例,这些示例说明了您可以在Spring中执行各种操作,并且通常有很多关于如何在Spring中执行操作的选择.

I would highly recommend reading the Spring reference materials and following the tutorials. The reference materials are very well written, easy to follow, and includes lots of examples on the various ways you can do things in Spring, and there are usually quite a few options on how you do things in Spring.

这篇关于Spring注解@ModelAttribute和@Valid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:10