5

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?

5
  • 5
    You need a renderer like JSP or thymeleaf Commented May 23, 2018 at 9:49
  • I'm not sure what that means but I think I tried using thymeleaf. I added "xmlns:th="thymeleaf.org"" to the html tag and tried making a label with "th:text="..."" to test, but it did the same thing. Do I also need a maven dependency? I can't find any (useful) tutorials or examples Commented May 23, 2018 at 9:53
  • post your current pom/ project structure. Commented May 23, 2018 at 9:55
  • ${variableName} use like this Commented May 23, 2018 at 10:07
  • Put your html code, please. Commented May 24, 2018 at 9:18

3 Answers 3

7

If you use Thymeleaf

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

what if this variable contains "<br/>" tag? Something like "hello <br/> world", but this does not work. hello world is showing in the same line instead of different lines
3

I figured it out. I was missing a dependency:

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

Comments

1

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;
}

5 Comments

That's what I'm doing. The reason I came to StackOverflow is because that documentation was unhelpful. They don't explain it very well. I don't know what I'm missing, it looks like it should be working
Did you change your variable ${attributeName} like that ?
Yes. I tried it by itself, I tried it with and without quotes, and I tried it as label text as th:text
Then I think problem is not here. Your thymeleaf does not work maybe.
Could you add your config file also ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.