[英]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.