简体   繁体   中英

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?

If you use Thymeleaf

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

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

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

I figured it out. I was missing a dependency:

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

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