JSF Tips

JSF tip – 1

Handling HTML forms is one of the most common tasks when you develop web applications. The JSF provides JSP tags for rendering HTML forms, manages the state of the forms, validates user-input reporting errors, lets you bind user interface components to JavaBean properties, and does many other things that increase your productivity.

JSF also has a rich API that you can use to build custom user interface (UI) components, custom validation classes (validators), and server-side event listeners. JSF contains two tag libraries called JSF Core and HTML Basic. The latter contains JSP tags that render HTML UI components such as buttons, text fields, checkboxes, lists, etc. In our example we use some of these tags to build the form.

The standard prefixes of these two tag libraries are f and h:

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<html>
<head>
<title>Edit</title>
</head>
<body>
<f:use_faces>
<h:form formName="sampleForm">
////////////// here we bind managed bean to text-area input:
<h:input_textarea id="text" valueRef="sampleBean.text" rows="3" cols="30">
<f:validate_required/>
</h:input_textarea>
<br><h:output_errors for="text"/>
<p><h:output_text value="This is a Label"/></p>
..........
</h:form>
</f:use_faces>
</body>
</html>

JSF Tip 2

Defining page navigation involves determining which page to go to after the user click a button or a link. Navigation for the application is defined in the application configuration resource file faces-config.xml using a rule-based system. Here the faces-config.xml file defines a navigation rule that tells JSF what to do when the user clicks one of the command buttons of the page whose path is specified within <from-tree-id>.

There are two navigation cases defined within separate elements because our page contains two buttons generated with . Each of them has an ID, a label, a command name:

A fragment of JSF page with form and command buttons:

<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
.........
<f:use_faces>
<h:form formName="manageAccount">
..........
<p>
<h:command_button id="withdraw" label="Withdraw money" action="withdraw"/>
<h:command_button id="deposit" label="Deposit money" action="deposit"/>
</h:form>
</f:use_faces> 

A navigation resource file:

..........
<faces-config>
<navigation-rule>
<from-tree-id>manageaccount.jsp</from-tree-id>

<navigation-case>
<from-outcome>withdraw</from-outcome>
<to-tree-id>withdraw.jsp</to-tree-id>
</navigation-case>

<navigation-case>
<from-outcome>deposit</from-outcome>
<to-tree-id>deposit.jsp</to-tree-id>
</navigation-case>
</navigation-rule>
..........
</faces-config>