An example of a simple button that triggers an action on the Controller side
Back to overviewThese buttons illustrate actions with and without parameters. They immediately get executed on the controller. Since a bean is a singleton instance, storing a variable in the controller itself would mean it is shared across all users. Instead, we can use the Session object to get the specific variables for the active user.
<div th:text="${counter}"></div>
<button m:click="updateCounter(1)">Increase counter</button>
<button m:click="reset()">Reset counter</button>
import io.getmedusa.medusa.core.annotation.UIEventPage;
import io.getmedusa.medusa.core.attributes.Attribute;
import io.getmedusa.medusa.core.session.Session;
import static io.getmedusa.medusa.core.attributes.Attribute.$;
import static io.getmedusa.medusa.core.attributes.Attribute.$$;
import java.util.List;
@UIEventPage(path = "/detail/basic-button", file = "/pages/basic-button.html")
public class Controller {
//This method gets called on page load and sets the initial values of variables
public List<Attribute> setupAttributes() {
//based on static import from Attribute class
return $$("counter", 0);
}
//This method takes a single parameter. The Session object can optionally be
//added as first or last parameter. It will be autofilled.
public List<Attribute> updateCounter(int amount, Session session) {
int counter = session.getAttribute("counter");
counter += amount;
//another way of writing attributes, based on static imports
return $$($("counter", counter));
}
//This method takes no parameters.
public List<Attribute> reset() {
//another way of writing attributes, without static imports
return List.of(new Attribute("counter", 0));
}
}