Binding different subtypes to a Spring MVC controller -


i have class hierarchy 1 class, say, book base class more specific item, childrensbook.

i need present these items in jsp form fields can edited. book , childrensbook have in common seems reasonable me use single controller , single jsp form. in fact childrensbook book 1 field, say,agegroup. jsp displays input box field when editing instances of childrensbook

i've begun write code i've hit problem when completed form posted mvc controller. here method handles form:

@requestmapping( value="*", method = requestmethod.post ) public string onsubmit( @valid @modelattribute("entity") bookcommand command, bindingresult result, redirectattributes redirectattributes, modelmap model ) { /* code not shown */ } 

as can see, i'm binding form bookcommand need forms children's books bind childrensbookcommand object.

what's solution in case? creating form / controller childrensbook cause lot of undesirable duplicated code. creating handler method childrensbookcommand instead of bookcommand fails, presumably because mvc cannot tell 1 use. posting children's book form different url seems awkward, since i'm using spring <form:form ...> tag automatically sets form action url.

thanks advice.

you can test object have when render jsp page , specify 2 different url. there 2 method in controller can call methods shared avoid duplicate code.

in jsp like

if(myobject book)   <form action="urlforbook"/> else   <form action="urlforchildrenbook"/> 

in controller, like

@requestmapping( value="/book", method = requestmethod.post ) public string onbooksubmit( @valid @modelattribute("entity") bookcommand command, bindingresult result, redirectattributes redirectattributes, modelmap model ) { commonmethod(); }  @requestmapping( value="/childrenbook", method = requestmethod.post ) public string onchildrenbooksubmit( @valid @modelattribute("entity") bookcommand command, bindingresult result, redirectattributes redirectattributes, modelmap model ) { commonmethod(); }  private commonmethod() { /* code goes here*/} 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -