简体   繁体   English

通过Spring将数据从Java传递到html

[英]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? 有没有办法将我的Spring控制器类中的String值传递给我的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. 在HTML中。 But when I load the page it shows literally ${variableName} instead of "someValue" 但是当我加载页面时,它显示${variableName}而不是"someValue"

Am I missing something? 我错过了什么吗?

If you use Thymeleaf 如果你使用Thymeleaf

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

You wrote: {$variableName} instead of ${variableName} 您写道:{$ variableName}而不是$ {variableName}

You can find thymeleaf documentation in here that show how to show model attribute in html. 你可以在这里找到thymeleaf 文档 ,展示如何在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. 在Thymeleaf中,可以使用以下语法访问这些模型属性(或Thymeleaf术语中的上下文变量): ${attributeName} ,其中attributeName在我们的例子中是消息。

    @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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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