问题
I'm working on an internal tool using spring-mvc and thymeleaf.
A section of this tool is used to create an entity we save in the database. This entity is quite complex; it contains many properties and relations. Some of these relations contain list and other properties.
I have 2 constraints:
- Single page. No "wizard".
- To only save a completed object in the database.
Now, I'm not really asking for a specific issue. I know my way around thymeleaf, spring @ModelAttribute, etc.
My question is mostly which strategy are you choosing or how to deal with really complex object creation.
Now I can see 3 ways to do it :
Rendering page with thymeleaf. Every time a new element need to be added to a list, I use Ajax to add the new element on the server and rerender the specific fragment. So doing back and forth to the server with my @ModelAttribute and only save at the end.
Rendering a basic page with thymeleaf. Using JavaScript to create html elements and instead of submitting to a @ModelAttribute, I'm serializing my form to JSON and submit this JSON to the server. (kind of client side model)
Rendering a basic page with thymeleaf. Create the html element dynamically with JavaScript when I need to add list item (being sure I'm putting proper name="" to fit with my Java form object) and submit the whole thing at the end.
I'm personally unsure between 1 or 2. I feel dealing with complex object is much more easier using JSON than form submission. Also, the input value/field with sub object and property can be quite nasty. Having this kind of syntax does not sound great to me...
3 can probably work but the way spring data binding is done with sub property is lacking some detail in my humble opinion (section 7.4.1 - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html).
What do you think ?
回答1:
Personally I use Thymeleaf's own dynamic field management to ensure clean addition of objects and fields to object.
So I will recommend option 4: Dynamic Field management by Thymeleaf.
Have a read of http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dynamic-fields.
I use that for both single field additions as well as addition of nested forms. Does the trick no questions asked.
Hope that helps.
来源:https://stackoverflow.com/questions/27768336/spring-mvc-thymeleaf-dealing-with-complex-form