Home > Enterprise >  Thymeleaf - parameter in method is always null
Thymeleaf - parameter in method is always null

Time:03-24

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);
    }

CodePudding user response:

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)}"

CodePudding user response:

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>
  • Related