[英]Spring Boot model.addAttribute - how to get message to display correctly?
我找到了以下示例來引導自己完成 SpringBoot 的一部分: 在此處找到
該示例可以正常運行,但我無法理解為什么 addAttribute 不會顯示已更改的消息,而是僅將“消息”作為字符串返回。
UPDATE @Controller注解的使用導致項目無法執行,作為解決方案,需要@RestController 。 我不確定這對一般問題是否有任何意義。
這是 controller 代碼:
package com.example.MySecondSpringBootProject.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String hello(){
return "hello";
}
@GetMapping("/message")
public String message(Model model) {
model.addAttribute("message", "This is a custom message");
return "message";
}
}
這是消息html頁面:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Demo Project</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
我在這里查看了 addAttribute 的各種實現,它們都使用來自前端的傳入值來為所述屬性分配一個值,這對該端點有意義,但在這種情況下,前端正在從中提取傳遞給它的值該方法的第二個參數 - 至少應該如此。
我試過這個,沒有效果:
@RequestMapping("/message")
public String message(Model model, @RequestParam(value="message") String message) {
model.addAttribute("message", "This is a custom message");
return "message";
}
在方法中傳遞第二個參數,同樣沒有效果,它只返回“消息”字符串:
@GetMapping("/message")
public String message(Model model, String str) {
model.addAttribute("message", "This is a custom message");
return "message";
}
我會繼續研究它,但此時我的腦袋開始轉圈,或者我只是不太了解 model.addAttribute 概念。
先感謝您!
試試這個解決方案:
@GetMapping("/message")
public String message(Model model) {
String msg = "This is a custom message" ;
model.addAttribute("msg", msg);
return "message";
}
對於視圖:
<h2 th:text="${msg}" align="center"></h2>
我希望這對你有幫助
您正在返回字符串“message”嘗試返回return model.addAtribute("message","this is custom message");
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.