英文:
thymeleaf doesn't update a model value in my template after a post
问题
@SessionAttributes("myNewAttribute") 是我在控制器顶部定义的一个会话属性。当我访问我的第二个端点,也就是 post 端点时,该值在 Thymeleaf 中没有从空白更新为字符串,但它确实打印到我的控制台上。我有点疯狂。这是我的控制器文件和模板文件:
@Controller
@SessionAttributes("myNewAttribute")
public class SpringFileController {
@GetMapping("/pageone")
public String displayPageOne(Model model) {
return "pageone";
}
@PostMapping("/clickedsavebutton")
public String handleSaveButton(Model model) {
model.addAttribute("myNewAttribute", "catnip");
String valueToDisplay = (String) model.getAttribute("myNewAttribute");
System.out.println(valueToDisplay);
return "pageone";
}
}
我的模板文件:
<p th:text="${myNewAttribute}"></p>
<!-- 保存按钮等其他内容... -->
所以,当我点击保存按钮后,控制台中会输出 "catnip",但在页面上,直到我刷新页面之前,不会显示 "catnip"。我做错了什么?
编辑:我在模板中的 post 调用之后添加了 window.location.reload()
,这会使属性显示出来,但这样做会导致页面上的其他更改丢失。
英文:
I have a session attribute called
@SessionAttributes("myNewAttribute")
which is defined at the top of my controller. when I hit my second endpoint, the post, the value does not update in thymleaf from blank to showing the string but it does print it to my console. I'm going a little crazy. Here is my controller file and my template:
@Controller
@SessionAttributes("myNewAttribute")
public class SpringFileController {
@GetMapping("/pageone")
public String displayPageOne(Model model) {
return "pageone";
}
@PostMapping("/clickedsavebutton")
public String handleSaveButton(Model model){
model.addAttribute("myNewAttribute","catnip");
String valueToDisplay = (String)model.getAttribute("myNewAttribute");
System.out.println(valueToDisplay);
return "pageone";
}
}
my template
<p th:text="${myNewAttribute}"></p>
<!--the save button, other things, wtc.. -->
So in my console when I click save I get "catnip" but "catnip" is not displayed on the page UNTIL I refresh the page. What am I doing wrong
edit: I added window.location.reload() after my post call in my template which makes the attribute show, but I lose other things on the page that have been changed if I do it this way
答案1
得分: 0
这是预期行为,Thymeleaf是一个渲染引擎,因此无法在页面初始加载后更改内容。
要实现期望的效果,您需要重新加载页面的(部分)内容。这可以是完全刷新,也可以使用类似ajax/javascript的方法来刷新一个div或字段。
英文:
This is expected behavior, Thymeleaf is a rendering engine and as such can not change things after the initial load of the page.
To get the desired effect you'd have to reload (part) of your web page. this can be either a complete refresh or refreshing a div or field using something like ajax/javascript.
答案2
得分: 0
我在保存按钮的函数中添加了以下代码,并使其正常工作。感谢您的所有帮助!
英文:
I added
$( "#required-field-div" ).load(window.location.href + " #required-field-div" );
to my function on the save button and got this to work. thank you for all the help!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论