I've been struggling with trying to get my commandButtons to perform an action (yet oddly, I have no problem pulling data from beans to include in my page). Have even posted up my code elsewhere and had it reviewed by others. So far, no luck. So, I'm thinking perhaps a different tact is in order. Can anyone point me to some very simple/basic sample code of a project that has a commandButton that is able to successfully call an action?
+1
A:
A common cause among starters is that the <h:form>
is been forgotten. As per the HTML specification, any submit button which is intented to submit something to the server side should be placed inside a HTML <form>
element.
Here's a simple Hello World how to do that in JSF:
JSF page
<!DOCTYPE html>
<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>Hello World</title>
</h:head>
<h:body>
<h:form>
Enter your name
<h:inputText value="#{bean.input}" />
<h:commandButton value="submit" action="#{bean.submit}" />
</h:form>
<h:outputText value="#{bean.output}" />
</h:body>
</html>
Bean:
package mypackage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class Bean {
private String input;
private String output;
public void submit() {
output = String.format("Hello %s!", input);
}
public String getInput() {
return input;
}
public String getOutput() {
return output;
}
public void setInput(String input) {
this.input = input;
}
}
That's all :)
For other possible causes of this problem, check the 1st link in the list below.
See also:
BalusC
2010-06-28 13:55:47
Excellent! Now the button actually does something instead of being ignored! (It just crashes now, but that's a solveable problem). :-)
Brian Knoblauch
2010-06-28 14:36:26
You're welcome. A hint for future problems: rightclick page in browser, view source and verify generated HTML output. If you're already a bit into webdev, you should have noticed the lack of `<form>` soon enough.
BalusC
2010-06-28 14:38:13
Last time I did webdev, we used CGI interfaces with C apps on the backend. I never would have noticed the missing <form>... :-)
Brian Knoblauch
2010-06-28 14:53:36