简体   繁体   中英

springboot with thymeleaf two way binding

I'm trying to use thymeleaf with 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:

<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. When I change the value of the input field. The values(that is myMap) in the model don't change.

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.

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.

If you want a back and forth communication between browser and server typically people use web sockets. Here's an example from spring.io on using websockets

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