I have a working JSF application that allows a user to enter their name, press the Submit button, and they are presented with a page that welcomes them.
The structure is very simple, there is a Person bean that has a setter and getter for a name, and the textfield sets the name, and the welcome page gets the name from the bean to present it on the welcome page.
My question is can I invoke java methods from XHTML when the user presses the Submit button, because I need to open a connection to the database. The code for the first page of the application looks like this in the xhtml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>JSF 2.0 Hello World</title>
</h:head>
<h:body>
<h3>JSF 2.0 Hello World Example - hello.xhtml</h3>
<h:form>
<h:inputText value="#{helloBean.name}"></h:inputText>
<h:commandButton value="Welcome Me" action="welcome"></h:commandButton>
</h:form>
</h:body>
</html>
So it looks like when they hit Welcome Me, the welcome.xhtml file is called up and the bean is passed to it. But I also need to execute some code to open the database when the Welcome Me button is pressed, how can I do this?
For that, the
actionattribute of the command button should be bound to the action method of the bean.In the method you’ve all the freedom to write down Java code which should be executed when the button is pressed.
The returned string will be used as navigation outcome. If you return
nullorvoid, it will return to the same view.See also: