"spring mvc conversion how to" Code Answer


thymeleaf compares values (for inclusion of selected="selected" tag in option html) using spring frameworks selectedvaluecomparator.isselected which inherently depends upon java equality first. if that fails, it falls back to string representation of both the values. following is excerpt from it's documentation

utility class for testing whether a candidate value matches a data bound value. eagerly attempts to prove a comparison through a number of avenues to deal with issues such as instance inequality, logical (string-representation-based) equality and propertyeditor-based comparison.
full support is provided for comparing arrays, collections and maps.
equality contract
for single-valued objects equality is first tested using standard java equality. as such, user code should endeavour to implement object.equals to speed up the comparison process. if object.equals returns false then an attempt is made at an exhaustive comparison with the aim being to prove equality rather than disprove it.
next, an attempt is made to compare the string representations of both the candidate and bound values. this may result in true in a number of cases due to the fact both values will be represented as strings when shown to the user.
next, if the candidate value is a string, an attempt is made to compare the bound value to result of applying the corresponding propertyeditor to the candidate. this comparison may be executed twice, once against the direct string instances, and then against the string representations if the first comparison results in false.

for your specific case, i'd write down conversion service so that my part object is converted to string as described for varietyformatter in http://www.thymeleaf.org/doc/html/thymeleaf-spring3.html#configuring-a-conversion-service . post this i'd use th:value="${part}" and let selectedvaluecomparator do it's magic of comparing the objects and add selected="selected" part in the html.

also in my design, i always implement equals method based on primary key (usually i do it at my top level abstract entity from which all other entities inherit). that further strengths the natural comparison of domain objects in my system throughout. are you doing something similar in your design?

hope it helps!!

By Carlos on June 7 2022

Answers related to “spring mvc conversion how to”

Only authorized users can answer the Search term. Please sign in first, or register a free account.