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.

Also Read:

The <h:form/> tag generates an HTML form element. for example, if, in a JSF pages named /index.xhtml, you use an h:form tag with no attributes, the Form renderer generates HTML like this:

<form id="_id0" method="post" action="/faces/index.html"
       enctype="application/x-www-form-urlencoded">

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 using of <h:commandButton/> or <h:commandLink/> without enclosing them within jsf form, cause no form submission.

1. Managed Bean

IndexBean.java

package net.javabeat.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class IndexBean {
	private String outcome = "index";
	private String userInput = "";

	public String getOutcome() {
		return outcome;
	}

	public void setOutcome(String outcome) {
		this.outcome = outcome;
	}

	public String getUserInput() {
		return userInput;
	}

	public void setUserInput(String userInput) {
		this.userInput = userInput;
	}

	public String submit(){
		this.userInput = "The user has entered \""+this.userInput+" \"";
		return "";
	}
}

2. The View

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
	<script>
		function check(){
			var message = document.getElementById("form:input");
			if(confirm("Are you sure sending message "+ message.value + " !")){
				return true;
			}
			return false;
		}
	</script>
</h:head>
<h:body>
	<h:form id="form">
		<h1>
			<h:outputText value="JavaBeat JSF 2.2 Examples" />
		</h1>
		<h2>
			<h:outputText value="JSF2 Form Example" />
		</h2>
		<h:outputText value="Enter Greeting Message : " />
		<h:inputText id="input" value="#{indexBean.userInput}" />
		<h:commandButton value="Submit" action="#{indexBean.submit}" onclick="return check();"/>
		<h:outputText value="#{indexBean.userInput}"/>
	</h:form>
</h:body>
</html>
  • The JavaScript is capable to locate the form’s component by using the expression formId:componentId.
  • The submit button (commandButton/commandLink) will not cause submission in case it’s not enclosed within a form.

3. The Deployment Descriptor (web.xml)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

	id="WebApp_ID" version="2.5" metadata-complete="true">
	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<context-param>
		<param-name>javax.faces.application.CONFIG_FILES</param-name>
		<param-value>/WEB-INF/faces-config.xml</param-value>
	</context-param>
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>
	<listener>
		<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
	</listener>
</web-app>
  • The state of the view has been saved by using the client methodology, so the jsf implementation will provide an input hidden for achieving that save.

4. The Translated Form

<html xmlns="http://www.w3.org/1999/xhtml"><head id="j_idt2">
	<script>
		function check(){
			var message = document.getElementById("form:input");
			if(confirm("Are you sure sending message "+ message.value + " !")){
				return true;
			}
			return false;
		}
	</script></head><body>
<form id="form" name="form" method="post" action="/JavaBeat-JSF-Installation/index.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="form" value="form">

		<h1>JavaBeat JSF 2.2 Examples
		</h1>
		<h2>JSF2 Form Example
		</h2>Enter Greeting Message : <input id="form:input" type="text" name="form:input" value="The user has entered &quot;Hello JavaBeat ! &quot;"><input type="submit" name="form:j_idt11" value="Submit" onclick="return check();">The user has entered "Hello JavaBeat ! "
<input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="fBTaoNkQRIl7YrSFyl44T8F96eXEe8iLJcL9n82xrPoB21m+OMee7vrrDxZLNpqidpXRfvCd/piHubd54c7hFwOEr7R8RNdihnLCc+3ASOmpJbJ8PTUw1vRk63DGv5oYooW06I2drUVYuv5oS/FC6UU3faddktGlxRu6PzAbHK5BisZz0I5pqxwuZpTw5D0YIEtjImnIUaDX2jqiMF+rsUvasLCnNNjGFOsstWDaYcZT0n2EoAyBMjvTYMfDlR+crLHKELW3zbVpwJBN3kyT5/LuI/wQpM0CMgm9Uuar7u1C6h3O8p+6A0AgNT2p+VDcfVIkcYYM1XTyr9o1iPy0sKlaatmdCt5z9r7S4nnQ8t2tyLgaDYIvUAiEXsfeKD+TVss7xqDRo57xgjwkD0jlyc51YQ6Ck27kGCCPqYU6X7rTj+NHm9gmqMFz3fobl1+AD2JpsTX12y7UFhIRNdb7y2TP4N0RQ4wmiB4t4MSEV9Kc6QV02X9fYyo6R7mFuuufj8Cby9hPHJuN7N3ZcdLsYUqtK7k53cVZOIIiX+toYggWYSSWwHD7xC9SdsoX9mIT" autocomplete="off">
</form>
</body></html>
  • 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.

JSF 2 Form Example

  • 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.
  • The submission has completed cause the submit button contained inside <h:form/>.

Comments

comments

About Amr Mohammed

Speak Your Mind

*