在春季将值从控制器传递到html [英] Passing value from controller to html in spring
问题描述
您好,我有一个简单的网页,其中有一个按钮和靠近按钮的文字.我需要在单击按钮时更改文本,然后从代码中获取新文本.
Hello I have a simple web page where I have a button and a text near to button. I need to change text when button clicked and get the new text from code.
这是我需要传递响应的控制器类:
This is controller class from where I need to pass response:
@GetMapping("/stream")
public String openStream(Model model) {
String response = service.openStream();
model.addAttribute("stream", response);
return "mainpage";
}
在我的html页面上,控制器的值必须不是问号:
And here my html page, the value from controller must be instead of question marks:
<div id="container">
<button class="button"
onclick="window.location.href = '/stream';">Stream</button>
<p align="center">?????</p>
</div>
预先感谢您的帮助.
我尝试了$ {stream}但将其作为文本获取价值时,请查看屏幕截图:
I tried ${stream} but getting it as text not value, please see screenshot:
我需要将字符串从文本区域传递到控制器中的doc变量.请帮忙.
Edit 2: I need pass String from the text area to doc variable in the controller. Please help.
HTML:
<div>
<textarea rows="10" cols="100" name="description"></textarea>
button class="button" onclick="window.location.href ='/send';">Send</button>
</div>
控制器:
@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);
通过HTML中的 $ {key}
获取价值
Get value by ${key}
in HTML
在Thymeleaf中,这些模型属性(或可以使用以下语法访问Thymeleaf术语:
$ {attributeName}
,其中本例中的attributeName是stream
.这是Spring EL表达式.简而言之,Spring EL(Spring Expression语言)是一种支持查询和操作对象图在运行时.
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.
UPDATE
UPDATE
可以在输入,选择或文本区域中使用th:field属性.
用
<input type="text" id="stream" name="stream" th:value="${stream}" />
或
<input type="text" th:field="*{stream}" />`
OR
<input type="text" id="stream" name="stream" th:field="*{stream}" th:value="${stream}" />
也尝试< p th:inline ="text"> [[$ {stream}]]</p>
;< p data-th-text ="$ {stream}"
/>
UPDATE 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";
}
注意:对于实体/模型,请使用"th:field"
这篇关于在春季将值从控制器传递到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!