jsf

TextBox Example with JSF 2.0

In this example, we are going to demonstrate a simple application, which purpose is to transfer data inserted to a page’s textbox (in our case, a sample username), to another page. While on JSF, we can use the following tag, in order to render an HTML input of a textbox: <h:inputText/>.

To get the meaning, imagine that the fore-mentioned xhtml’s tag is equal to HTML’s <input type="text">. So, let’s get into the full example.
 
 
 
 

1. Managed Bean

Here is our simple Managed Bean, which handles the username.

UserBean.java

package com.javacodegeeks.enterprise.jsf.textbox;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class UserBean implements Serializable{

	private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

2. Our Pages

Like we said, we need two separate pages; the first will get the user’s input and the second will render it back. 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 TextBox Example</title>
    </h:head>
    <h:body> 
    	<h1>JSF 2.0 TextBox Example</h1>

    	<h:form>
    		<h:inputText value="#{userBean.username}" />
    		<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 TextBox Example</title>
    </h:head>
    <h:body> 
    	<h1>JSF 2.0 TextBox Example - Response Page</h1>

    	Welcome, <h:outputText value="#{userBean.username}" /> !
    </h:body>
</html>

3. Demo

Now that we got our two view pages set up, let’s have a quick demo, by trying to access the following URL: http://localhost:8080/TextboxJSF

textboxJSF1

And after clicking the button, our response page:

textboxJSF2

This was an example of TextBox in JSF 2.0. You can also download the source code of this example: TextboxJSF

Thodoris Bais

Thodoris is an Oracle Certified Associate Java Programmer and currently works as a Junior Software Developer, for Intrasoft International S.A. He holds a diploma at Informatics & Telecommunications Engineering and is interested in continuous development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button