您的位置:首页 > 编程语言 > Java开发

Binding Entities and Their Children to Java JSP Form Elements in Spring Framework MVC

2013-04-08 10:22 555 查看
Binding objects to JSP form elements is actually quite easy in Spring Framework using the “modelAttribute” and “path” tags. Our scenario was the use of two Hibernate POJOs comprised of a parent entity “Parent” and a single “Child” entity which needed to be
displayed on screen with appropriate form elements (“input” and “select”). The entities were annotated for use as part of a larger application but the basic structure was:

To display these objects on screen as part of a form in Spring Framework MVC we used the following “ParentController” controller with a “showparent” action. The action uses a “parentService.getParent(id)” method (not shown) to retrieve a single parent entity
based on “id” and attach it to the form using a Map “model” and a returned “ModelAndView”. A “ch
14ff2
ildService” is used to get the list of every possible child entity (also not shown) and this is also added to the “ModelAndView”:

The form itself is very simple and uses Spring binding to automatically create and populate input fields:

Spring Framework uses the “modelAttribute” and “path” tags to determine what is set on the form. In this case the forms “modelAttribute” is “parent” which means that the elements in the form are properties of the “parent” entity. The “description” is shown
as the contents of a simple textbox input using “form:input”. The interesting part is the “form:select” which automatically populates the select with option objects based on the set of “child” objects in “children” and selects the correct “child” option for
the “parent” based on the “itemValue”, “id” in this case.

Submitting changes to “parent” entities is covered
in my more recent post.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐