您好,我有一个简单的网页,其中有一个按钮和按钮附近的文本。我需要在单击按钮时更改文本并从代码中获取新文本。
这是我需要传递响应的 Controller 类:
@GetMapping("/stream")
public String openStream(Model model) {
String response = service.openStream();
model.addAttribute("stream", response);
return "mainpage";
}
这里是我的 html 页面,来自 Controller 的值必须是而不是问号:
<div id="container">
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
<p align="center">?????</p>
</div>
预先感谢您的帮助。
编辑: 我试过 ${stream} 但是把它作为文本而不是值,请看截图:
编辑 2: 我需要将文本区域中的字符串传递给 Controller 中的 doc 变量。请帮忙。
HTML:
<div>
<textarea rows="10" cols="100" name="description"></textarea>
button class="button" onclick="window.location.href ='/send';">Send</button>
</div>
Controller :
@GetMapping("/send")
public String send(String doc) {
service.sendDoc(doc);
return "mainpage";
}
最佳答案
改变
<p align="center">?????</p>
到
<p align="center">${stream}</p> OR <p th:text="${stream}"></p>
它是如何工作的?
您可以通过 ${key} 访问变量值。
示例
model.addAttribute("key", value);
通过 ${key}
获取值在 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 isstream
. This is a Spring EL expression. In short, Spring EL (Spring Expression Language) is a language that supports querying and manipulating an object graph at runtime.
更新
th:field 属性可用于输入、选择或文本区域。
替换<p align="center">?????</p>
与
<input type="text" id="stream" name="stream" th:value="${stream}" />
或
<input type="text" th:field="*{stream}" />`
或
<input type="text" id="stream" name="stream" th:field="*{stream}" th:value="${stream}" />
也试试 <p th:inline="text">[[${stream}]]</p>
; <p data-th-text="${stream}"
/>
Thymeleaf Document Thymeleaf Document Inputs
更新 2
从 Thymeleaf 到 Spring Boot 获取值(value)
<form th:action="@{/send}" method="get">
<textarea th:name="doc" rows="10" cols="100" name="doc"></textarea>
<button type="submit">Send</button>
</form>
@GetMapping("/send")
public String send(@RequestParam(name="doc", required = false) String doc) {
//change required = false as per requirement
System.out.println("Doc: "+doc);
return "textarea-input";
}
注意:实体/模型使用“th:field”
关于java - 在 spring 中将值从 Controller 传递到 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56991362/