0

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);
    }
shane_00
  • 101
  • 1
  • 2
  • 9
  • Does this answer your question? [how to access variables in thymeleaf templates using spring mvc](https://stackoverflow.com/questions/44319070/how-to-access-variables-in-thymeleaf-templates-using-spring-mvc) – pringi Mar 23 '22 at 09:52
  • no, the parameter that I receive in the controller for some reason is still null – shane_00 Mar 23 '22 at 09:54
  • You want to call a method from thymeleaf. I did not see that in the first comment. Check this one: https://stackoverflow.com/questions/43841458/how-to-call-a-service-method-with-thymeleaf – pringi Mar 23 '22 at 09:58
  • yes, the argument call is fine it works but I cant pass a parameter through it, I pass 1 to postCount(1) but inside the method I get that the value for it is null: "java.lang.NullPointerException: null at com.example.forumproject.controllers.mvc.CategoryMvcController.getPostsCountInCategory(CategoryMvcController.java:56) " – shane_00 Mar 23 '22 at 10:03

2 Answers2

1

I suspect the problem is not in your code, but in this annotation: @ModelAttribute("postsCount") -- which is probably trying to put postsCount onto the model by calling getPostsCountInCategory(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.

@Controller
public class Controller() {
    @Autowired private PostCounter postCounter;
    
    $Get("category/")
    public String loadView(Model model) {
        model.put("postCounts", postCounter.getPostsCountInCategory(1));
    }
}

And in the HTML:

<p th:text="${postsCount}"></p>
Metroids
  • 18,999
  • 4
  • 41
  • 52
0

In Thymeleaf, you can not just call a method without object reference. You can do something like this:

Java Code:

//Make sure that, this class will be in IOC as bean
@Bean
public class PostCountHelper {
public int postCount(int count) {
//your handling logic goes here & count will have value which you passed
}
}

@Controller
public class PostCountController() {
private PostCountHelper postCountHelper;
public String loadView(Model model) {
model.put("postCountHelperReference", postCountHelper);
}
}

Thymeleaf Code:

<p th:text="${postCountHelperReference.postCount(1)}"
Abhale Amol
  • 109
  • 4