Textarea Example with JSF 2.0
In this example of JSF Tag Library series, we are going to show an effective way to implement a textarea field. Suppose that we want to insert a textarea of 20 columns and 10 rows. In HTML, this means <textarea cols="20" rows="10"></textarea>
. According to JSF, we can use the following tag, to implement it: <h:inputTextarea cols="20" rows="10" />
.
So, let’ s get the work done!
1. Managed Bean
As usually, I’ll first provide the source code for the Managed Bean, but for this time, we ‘ll hack it a little bit, by changing its name property, to user
. That is, our web pages, can refer to the Managed Bean by using the custom names that we had given to them, during development.
UserBean.java
package com.javacodegeeks.enterprise.jsf.textarea; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="user") @SessionScoped public class UserBean implements Serializable{ private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
2. Our Pages
As in the previous example, we need two separate pages; Let’s have a look at them:
index.xhtml
<?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:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF Textarea Example</title> </h:head> <h:body> <h1>JSF 2.0 Textarea Example</h1> <h:form> <table> <tr> <td valign="top">Address:</td> <td><h:inputTextarea> value="#{user.address}" cols="20" rows="10" /></td> </tr> </table> <h:commandButton value="Submit" action="response" /> </h:form> </h:body> </html>
response.xhtml
<?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:h="http://java.sun.com/jsf/html"> <h:head> <title>JSF Textarea Example</title> </h:head> <h:body> <h1>JSF 2.0 Textarea Example - Response Page</h1> Your address is : <h:outputText value="#{user.address}" /> </h:body> </html>
3. Demo
Let’s take a quick demo, by trying to access the following URL: http://localhost:8080/TextareaJSF
And after clicking the button, our response page:
4. Some Closing Words
There is a chance to get an execution error; you will be informed that the class user
cannot be found. In this case, we usually try to handle the Managed Bean’s name annotation by hand, by simply adding a managed bean dependency in faces-config.xml
file. For this reason, I’m attaching this version of the project, just in order to keep every newbie to J2EE following along, without facing any difficulty.
This was an example of Textarea in JSF 2.0. You can also download the source code for this example: TextareaJSF