Thymeleaf - 方法中的参数始终为空
我是百里香新手,遇到以下问题。我想在 html 模板中调用 java 方法,但该方法需要一个参数,但问题是无论我传递什么参数,结果始终为 null。
categories.html:
<p th:text="${postsCount(1)}"></p>
类别控制器:
@ModelAttribute("postsCount")
public int getPostsCountInCategory(Integer categoryId) {
return categoryService.getPostsCountInCategory(categoryId);
}
I am new to thymeleaf and I have the following problem. I want to call a java method inside the html template but the method needs an argument but the issue is that no matter what I am passing for an argument the result is always null.
categories.html:
<p th:text="${postsCount(1)}"></p>
categoryController:
@ModelAttribute("postsCount")
public int getPostsCountInCategory(Integer categoryId) {
return categoryService.getPostsCountInCategory(categoryId);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑问题不在您的代码中,而是在这个注释中:
@ModelAttribute("postsCount")
——它可能试图通过调用将postsCount
放入模型中getPostsCountInCategory(null)
因为它不知道要提供什么值。话虽如此,您确实不应该在 HTML 代码中调用数据库方法。不能保证它们只会被调用一次,并且您违反了模型/视图/控制器分离。您应该将这些值添加到您的模型中,并将其显示在您的页面上。
在 HTML 中:
I suspect the problem is not in your code, but in this annotation:
@ModelAttribute("postsCount")
-- which is probably trying to putpostsCount
onto the model by callinggetPostsCountInCategory(null)
because it doesn't know what value to supply.That being said, you really shouldn't be calling database methods in your HTML code. There is no guarantee they'll only be called once, and you are violating the model/view/controller separation. You should be adding the values to your model, and displaying that on your page.
And in the HTML:
在 Thymeleaf 中,您不能只调用没有对象引用的方法。
你可以这样做:
Java代码:
Thymeleaf代码:
In Thymeleaf, you can not just call a method without object reference.
You can do something like this:
Java Code:
Thymeleaf Code: