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");
}
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With