简体   繁体   English

springboot 与 thymeleaf 两种方式绑定

[英]springboot with thymeleaf two way binding

I'm trying to use thymeleaf with springboot.我正在尝试将百里香与springboot一起使用。 but some problems happened and I don't why.但是发生了一些问题,我不知道为什么。

Here's my code:这是我的代码:

@GetMapping
public String main(Model model) {

    Map<String, String> map = new HashMap<>();
    map.put("field1", "value1");
    map.put("field1", "value1");

    model.addAttribute("myMap", map);
    return "index";
}

and here's the html:这是html:

<div class="nav" th:each="myEntry:${myMap}">
     <label th:text="${myEntry.getKey()}"></label>
     <input th:value="${myEntry.getValue()}">
     <button class="btn" th:onclick="'javascript:trigger()'">Trigger</button>

</div>

As you can see in the java and html。I set a key-value pair for the model, and use it's key as a label, value as a input.如你在java和html中看到的。我为模型设置了一个键值对,并使用它的键作为标签,值作为输入。 When I change the value of the input field.当我更改输入字段的值时。 The values(that is myMap) in the model don't change.模型中的值(即 myMap)不会改变。

Anyone knows why or how?任何人都知道为什么或如何?

The way that thymeleaf works here is that it takes the template, injects the model and serves it to the client, this is called server side rendering. thymeleaf 在这里工作的方式是它获取模板,注入模型并将其提供给客户端,这称为服务器端渲染。

When you change the value in the input field you are making changes client side and the HTML is not related to the server side at all, as all backend does is serves your page.当您更改输入字段中的值时,您正在更改客户端并且 HTML 与服务器端完全无关,因为所有后端都为您的页面提供服务。

If you want a back and forth communication between browser and server typically people use web sockets.如果您想在浏览器和服务器之间进行来回通信,通常人们使用 Web 套接字。 Here's an example from spring.io on using websockets这是spring.io 中关于使用 websockets的示例

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

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