Search code examples
javaspringspring-bootthymeleafhashset

Automatically convert HashSet to concatenated string in Spring Boot


I'm fairly new to Spring Boot and am currently working on a form for a CMS to create an article. The article has keywords that are similar to SO's tag system. For now, it's a simple comma-separated list of keywords. However, I'm running into an issue when trying to rely on thymeleaf to convert my Command object into the format I want. Here are the relevant objects:

@Setter
@NoArgsConstructor
public class ArticleCommand {
    private Long id;
    private String title;
    private String slug;
    private String summary;
    private String body;
    private Set<ArticleKeywordCommand> keywords = new HashSet<>();
}
@Getter
@Setter
@NoArgsConstructor
public class ArticleKeywordCommand {
    private ArticleKeywordsKey id;
    private Long articleId;
    private KeywordCommand keyword;

    @Override
    public String toString() {
        return keyword.getName();
    }
}

As you can see, I added a toString() method to ArticleKeywordCommand in an effort to have the form, which outputs the value of keywords into an input field, contain the values as a comma-separated list. This...sort of works, but isn't what I'm looking for.

The output of ArticleCommand.keywords is an array of strings, "[technology, finance]". What I need instead is just a string "technology, finance".

What's a good way to handle transforming the output of the Set of keywords? Is there something in Thymeleaf to concat the values into a string when it receives a set? Or maybe an annotation I could provide to the Command that tells it how to handle it?


Solution

  • You could use #strings.listJoin within thymeleaf: https://www.thymeleaf.org/apidocs/thymeleaf/3.0.0.RELEASE/index.html?org/thymeleaf/expression/Strings.html (it doesn't appear to allow me to anchor link on that page, so just search for listJoin)

    For example if your model name is articles, the thymeleaf could look something like this:

    <p th:text="${#strings.listJoin(articles.getKeywords(), ', ')}"></p>