Spring-mvc + Thymeleaf: dealing with complex form

霸气de小男生 提交于 2020-02-27 03:24:15

问题


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:

  1. Single page. No "wizard".
  2. 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 :

  1. 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.

  2. 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)

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!