简体   繁体   中英

How to print a java object inside the thymeleaf template?

I need to show the model data of the resultset object in a price.html which consist with thymeleaf. What is the way of accessing sub elements of resultset object. Is there any way to print the whole object . just like toString(). This is my Controller class in spring-boot

@PostMapping("/price")
public ModelAndView pricePost(@Valid @ModelAttribute("priceSearch") PriceSearch priceSearch, 
        BindingResult bindingResult, Model model) {
    modelAndView.addObject("resultSet", resultSet);
    modelAndView.setViewName("price");
    return modelAndView;
}

There's no generic way in java to "toString" any random object out of the box if that is what you are looking for. You'll be left to iterating through the items of resultSet and printing it's properties directly.

If you need just any textual representation of your object, you could marshal it to JSON in oder to have a look at it.

If you want to access the sub elements of the resultset object using thymeleaf, you would need to do something like this.

<th:block th:each="iterator : ${resultSet}">
     <p th:text=${iterator.name}></p>
</th:block>

Note: I am assuming that resultset is a collection of objects.

You can override the toString() method of the object-class. Feel free to iterate over nested sub-elements and add their toString()-response to the returned value, eg:

@Override
public String toString()
{
  String result = /* other properties from the class */ 
  result += "[";
  for (SubElementClass o in this.subElements)
  {
     result += String.Format("(%s)", o.toString());
  }
  result += "]";
  return result;
}

It make sense to override to toString() method in the SubElementClass, too.

Another option is not to override the toString method but add a dump() method to a extended class of your original class, which you can called in the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM