java - 在 spring 中将值从 Controller 传递到 html

标签 java spring spring-boot spring-mvc thymeleaf

您好,我有一个简单的网页,其中有一个按钮和按钮附近的文本。我需要在单击按钮时更改文本并从代码中获取新文本。

这是我需要传递响应的 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} 但是把它作为文本而不是值,请看截图: enter image description here

编辑 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 is stream. 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/

相关文章:

java - 无法使用 IntelliJ IDEA 打开项目

java - JPA 更改不会保留在数据库中

java - 无法将 JavaTimeModule 导入 Spring Boot 配置类

java - 为什么这个 while 循环会这样?

java - 正则表达式帮助 -- 忽略引号之间的内容

java - 如何使用 SockJs 通过 STOMP Java 客户端验证 Spring 非 Web Websocket?

spring-boot - Elasticsearch 结果与搜索键不匹配

java - 了解 Eureka 客户端缓存

java - 每个路径 Spring 多个 HandlerMethodArgumentResolver

java - Java运行时真的没有 secret 的流复制方法吗?