Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Spring Basics Modeling, Storing, and Presenting Data Using @PathVariable to Create a Dynamic Detail Page

Jordan George
Jordan George
9,926 Points

model.put("gif", gif); meaning?

Does model.put("gif", gif) correspond to the gif.name in <img th:src="@{'/gifs/' + ${gif.name} + '.gif'}" alt="gif" />? I'm just having a hard time understanding the put for the ModelMap.

    @RequestMapping("/gif")
    public String gifDetails(ModelMap model) {
        Gif gif = new Gif("compiler-bot", LocalDate.of(2016,8,15), "Jordan George", true);
        model.put("gif", gif);
        return "gif-details";
    }


 <img th:src="@{'/gifs/' + ${gif.name} + '.gif'}" alt="gif" />

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

When you type model.put("gif", gif), you put whole gif object with all its method and properties to be available in Thymeleaf template, like

  • ${gif.name} - corresponding to gif.getName()
  • ${gif.username} - corresponding to gif.getUsername()
  • ${gif.favorite} - corresponding to gif.isFavorite() (note how it takes boolean getters into consideration)

You can even use specific method on gif, if you want, you can write:

<img th:src="@{'/gifs/' + ${gif.getName()} + '.gif'}" alt="gif" />

You also can type just this

<img th:src="@{'/gifs/' + ${gif} + '.gif'}" alt="gif" />

In this case toString() method will be used of gif object.

You can also put String someString = "some string" in the model model.put("string", someString). Then in Thymeleaf you can write like this:

<img th:src="@{'/gifs/' + ${string} + '.gif'}" alt="gif" />