Sam*_*nov 3 java spring spring-mvc thymeleaf spring-boot
您好,我有一个简单的网页,其中有一个按钮和靠近按钮的文本。我需要在单击按钮时更改文本并从代码中获取新文本。
这是我需要传递响应的控制器类:
@GetMapping("/stream")
public String openStream(Model model) {
String response = service.openStream();
model.addAttribute("stream", response);
return "mainpage";
}
Run Code Online (Sandbox Code Playgroud)
在这里我的 html 页面,来自控制器的值必须不是问号:
<div id="container">
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
<p align="center">?????</p>
</div>
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助。
编辑:我试过 ${stream} 但将其作为文本而不是值,请看截图:

编辑 2:我需要将字符串从文本区域传递到控制器中的 doc 变量。请帮忙。
HTML:
<div>
<textarea rows="10" cols="100" name="description"></textarea>
button class="button" onclick="window.location.href ='/send';">Send</button>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
@GetMapping("/send")
public String send(String doc) {
service.sendDoc(doc);
return "mainpage";
}
Run Code Online (Sandbox Code Playgroud)
改变
<p align="center">?????</p>
Run Code Online (Sandbox Code Playgroud)
到
<p align="center">${stream}</p> OR <p th:text="${stream}"></p>
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?
您可以通过 ${key} 访问变量值。
例子
model.addAttribute("key", value);
Run Code Online (Sandbox Code Playgroud)
${key}在 HTML 中获取值
在Thymeleaf,这些模型属性(或上下文变量在Thymeleaf行话),可以用下面的语法来访问:
${attributeName},其中的attributeName在我们的例子是stream。这是一个 Spring EL 表达式。简而言之,Spring EL(Spring Expression Language)是一种支持在运行时查询和操作对象图的语言。
更新
th:field 属性可用于输入、选择或文本区域。
替换 <p align="center">?????</p>为
<input type="text" id="stream" name="stream" th:value="${stream}" />
Run Code Online (Sandbox Code Playgroud)
或者
<input type="text" th:field="*{stream}" />`
Run Code Online (Sandbox Code Playgroud)
或者
<input type="text" id="stream" name="stream" th:field="*{stream}" th:value="${stream}" />
Run Code Online (Sandbox Code Playgroud)
也试试 <p th:inline="text">[[${stream}]]</p>;<p data-th-text="${stream}"/>
更新 2
从 Thymeleaf 到 Spring Boot 获取价值
<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";
}
Run Code Online (Sandbox Code Playgroud)
注意:实体/模型使用“th:field”
| 归档时间: |
|
| 查看次数: |
8268 次 |
| 最近记录: |