Andrew Torr
Andrew Torr

Reputation: 1127

Passing data into html from Java via Spring

Is there a way to pass a String value from my Spring controller class to my HTML? In various "hello world" examples, they say to use

ModelAndView model = new ModelAndView("htmlPageName");
model.addAttribute("variableName", "someValue");

in the controller and

${variableName}

in the HTML. But when I load the page it shows literally ${variableName} instead of "someValue"

Am I missing something?

Upvotes: 5

Views: 13197

Answers (3)

Andrew Torr
Andrew Torr

Reputation: 1127

I figured it out. I was missing a dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

Upvotes: 3

Hatice
Hatice

Reputation: 944

You can find thymeleaf documentation in here that show how to show model attribute in html.

In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName}, where attributeName in our case is messages.

    @RequestMapping(value = "message", method = RequestMethod.GET)
    public ModelAndView messages() {
        ModelAndView mav = new ModelAndView("message/list");
        mav.addObject("messages", messageRepository.findAll());
        return mav;
}

Upvotes: 1

Rafał Sokalski
Rafał Sokalski

Reputation: 2007

If you use Thymeleaf

<h1 th:text="${variableName}"></h1>

You wrote: {$variableName} instead of ${variableName}

Upvotes: 7

Related Questions