2

I'm using Thymeleaf and Spring. I have a page on which I want to populate some fields and I'm passing in a Map object to the page model using model.addAttribute as below. pbObject is a PassbackObject that we're using to pass data between form pages.

Map<String, Object> formData = new HashMap<>();
formData.put("station", station);
pbModel.setFromPriorForm(formData);
model.addAttribute("pbObject", pbModel);
System.out.println("The station object is: " + formData.get('station'));
System.out.println("The class of the Station object is: " + formData.get("station").getClass());

The two print statements return the station object and org.unavco.web.response.obj.Station as expected so the object types are fine here.

The problem arises when I try to access the Map object in Thymeleaf.

<input th:value="${pbObject.fromPriorForm.get('station').getClass()}"/>

The above code populates the input field with class java.lang.String. It's not a String!!! It's a Station! And yes, it's seeing the correct data because if I remove .getClass() I see the correct data (apparently as a String). I need to be able to access the object attributes later on so a String won't cut it. Why is Thymeleaf casting my mapped object to a String? How can I make it preserve the original object class?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
medley56
  • 1,181
  • 1
  • 14
  • 29
  • HTML values will always be strings. No? – holmis83 Feb 01 '18 at 20:01
  • @holmis83 Maybe that is how this works but `getClass()` is definitely a Java method and it returns a Java class type so Thymeleaf is doing some Java stuff back there. I don't fully understand how Thymeleaf talks to Spring though. – medley56 Feb 01 '18 at 20:10
  • Have you tried mapping the values of your object into a hidden class and setting your form th:object="pbObject type" then, when you return it back as a ModelObject, the model will populate an object using the framework you specified. – Jolley71717 Apr 06 '18 at 22:06

0 Answers0