How to bind spring MVC jsp page to two classes
I have two classes Person and Passport. Passport has foreignkey = personid.
This is my controller
model.addAttribute("personAttribute", new Person());
JSP PAge
<form:form modelAttribute="personAttribute" method="POST" action="${saveUrl}">
<table>
<tr>
<td><form:label path="firstName">First Name:</form:label></td>
<td><form:input path="firstName"/></td>
<td><form:errors path="firstName"/>gfgf</t开发者_如何学JAVAd>
</tr>
<td><form:label path="country_issue">Passport:</form:label></td>
<td><form:input path="country_issue"/></td>
<td><form:errors path="country_issue"/></td>
NOw i want to put country_issue in other passport table.
I don't have that column in Person so how will i bind that in JSP page
Passport has only id , person_id, country_issue field
All you have to do is wrap your form backing objects in a form:
public class MyForm
{
private final Person person;
private final Passport passport;
public MyForm()
{
this.person = new Person();
this.passport = new Passport();
}
public MyForm(Person person, Passport passport)
{
this.person = person;
this.passport = passport;
}
// getters & setters
}
Then in your controller:
model.addAttribute("myForm", new MyForm());
or you could do
model.addAttribute("myForm", new MyForm(personService.findPerson(1), passportService.findPassport(1)));
and in your jsp:
<form:form modelAttribute="myForm" method="POST" action="${saveUrl}">
<table>
<tr>
<td><form:label path="person.firstName">First Name:</form:label></td>
<td><form:input path="person.firstName"/></td>
<td><form:errors path="person.firstName"/>gfgf</td>
</tr>
<tr>
<td><form:label path="passport.country_issue">Passport:</form:label></td>
<td><form:input path="passport.country_issue"/></td>
<td><form:errors path="passport.country_issue"/></td>
<tr/>
</table>
</form>
I would suggest you to create a class that maps your GUI form 1:1 and then write a transformer/validator. This class should ideally be package-private (maybe even inner class) for your GUI element so it doesn't mix with the DAO objects, such as Person
or Passport
.
UI data is managed best with Classes like TransferObjects are ModelObjects which represent the page data binding requirements. If we do that we can move the concern to the controller to extract out the spring (persistent) objects from the UI object.
If the object is called PassportForm then the method passportForm.person() and passportForm.Passport() should give you the persistent object. In this way we can also eliminate the need for transformer/validator classes and push the behavior into the objects.
精彩评论