JSF 2 Form Example

Most of web applications run on a form submission, and JSF 2 applications are not exception. The <h:form/> is the component that’s responsible for allowing the <h:commandButton/> and <h:commandLink/> to submit the view back to the server. The content type that’s used for submission is by default application/x-www-form-urlencoded, once you’ve omitted providing the attribute enctype. Those values that can be passed for such that property listed as follow:

application/x-www-form-urlencoded: it’s the default, all characters are encoded before sent (spaces are converted to + symbols, and special characters are converted to ASCII HEX values.

mulipart/form-data: No characters are encoded. This value is required when you are using forms that have a file upload control.

text/plain: Spaces are converted into + symbols, but no special characters are encoded.

Although the HTML form tag has method and action attribute, h:form does not, because you can save state in the client – an option that’s implemented as a hidden field – and posting forms with the GET is disallowed. The contents of that hidden field can be quite large and may overrun the buffer for request parameters, so all JSF form submissions are implemented with the POST method. There is no need for anchor attribute since JSF form submission always post to the current page. Navigation to a new page happens after the form data have been posted, since the navigation handler consider the token that’s returned back from the action that have been called.

If you don’t specify the id attribute explicitly, a value is generated by the JSF implementation, as is the case for all generated HTML elements. You can explicitly specify the id attribute for forms so that it can be referenced in stylesheets or scripts.

All form controls generated by JSF implementation have names that conform to (formName:componentName) where formName represents the name of the control’s form and componentName represents the control’s name. If you don’t specify id attributes, the jsf implementation creates identifiers for you.

The jsf implementation does create an input hidden for achieving the save state of the view.

The jsf implementation does generate the identifiers for the form components, so if you’ve noted the input identifier you should see it identified like form:input, where the form id is form and the input id is input.

5. JSF Form Demo

The below snapshot shows you the complete scenario of using the form component.

The user has submitted the message and the backing bean will add the text (The user has entered) for the message that entered by the user.

The submit button will invoke a java script method check once it’s clicked and that function will identify the input value using the component that identified by the java script getElement.

So the backing bean method submit has returned an empty string the view will be re displayed.