2018-04-03

Add or remove items from a list of objects in a model attribute using Spring MVC and Thymeleaf

In a Spring MVC application I have a model with a List type attribute. The model is bound to a HTML form and rendered by Thymeleaf. The goal is to be able to add or remove items from the list and to submit the form with modified list. All of that with and without JavaScript.

There are few solutions for this problem available on the internet but none of those which I found was clean and simple enough. There has been some request interceptors, List interface custom implementations, etc.

The idea behind this solution is simple. In a controller there are four endpoints. Two are used for rendering and "saving" the model. Two for adding and removing items from the list. Later two can be invoked as a standard HTTP request or as an Ajax request. This will ensure that solution will work with or without JavaScript enabled.

Thanks to Thymeleaf's fragments there is only one template needed. By default, on an HTTP request all endpoints returns whole page. If Ajax request is sent, smaller part of the page containing the list will be returned.

Ability to not to re-render whole page on every HTTP request makes user experience more seamless. Following jQuery snippet will a) call the endpoints for adding or removing inems from list and b) replace #items fragment by returned content.