'How to set a button onclick event and link to Thymeleaf controller?

I am trying to write some code where, once the user clicks a button, it will do some set of code in my Thymeleaf controller class. I tried looking on other various code found here on stackoverflow, however, I was not able to find a proper solution. The error I get is that the code will not print out the desired statement.

Code:

<button type="button" th:onclick="doStuffMethod()"> Hello</button>

Controller:

    public void doStuffMethod() {
        System.out.println("Success");
    }



Solution 1:[1]

A simple way can achieve this by following 2 steps:

Step 1: Make doStuffMethod to be visited with /do-stuff

@RequestMapping(value="/do-stuff")
public void doStuffMethod() {
    System.out.println("Success");
}

Step 2: Use window.location.href to visit /do-stuff

<button type="button" th:onclick="|window.location.href='/do-stuff'|">Hello</button>

All above this can invoke your doStuffMethod() successfully after pressing the button, but it is going to throw some exception due to no template called do-stuff.
Therefore, a better way is to create a template called doStuff.html and return it's name as string in doStuffMethod().

doStuff.html

<h1>Success</h1>

And modify your controller as follows:

@RequestMapping(value="/do-stuff")
public String doStuffMethod() {
    System.out.println("Success");
    return "doStuff";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1