Struts JSF
High level overview of JSF
Login page
8
Welcome page
9
Example files
index.jsp,welcome.jsp – define the login and welcome
screens.
UserBean.java – manages user data
faces-config.xml – configuration file for the application.
web.xml – deployment descriptor.
10
JSF Example(index.jsp)
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:loadBundle basename=“com.corejsf.bundle.Messages" var="Message"/>
<f:view>
…
<h:form>
<h3><h:outputText value="#{Message.inputname_header}"/></h3>
<table>
<tr>
<td>Name:</td>
<h:inputText value="#{user.name}“ required=“true”/>
<f:validateLength minimum="2" maximum="20"/>
…
<td>Password:</td>
<h:inputSecret value="#{user.password}"/>
…
<h:commandButton value="Login" action="login"/>
</h:form>
</f:view>
11
index.jsp
• Tag Libraries: core and html.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
• Core tags are used to perform core actions and display nothing to the user.
Html tags are used to render html elements(text, form elements etc) to
the user.
• <f:loadBundle> is a core tag. Loads properties file and makes it value
available to variable message.
<f:loadBundle basename=“com.corejsf..bundle.Messages" var="Message"/>
• All JSF components must be nested inside <f:view> core tag.
<f:view>
<h:form>
<h3><h:outputText value="#{Message.inputname_header}"/></h3>
<h:inputText value="#{user.name}“ required=“true”/>
<f:validateLength minimum="2" maximum="20"/>
<h:inputSecret value="#{user.password}"/>
<h:commandButton value="Login" action="login"/>
</h:form>
</f:view>
12
Example (Cntd.)
• Any attribute value that starts with # and is wrapped in {} is dynamically
substituted in
#{Message.inputname_header}
• <h:inputText> for name field renders a textbox. Required attribute tells the
value must be provided by the user. Thus validating the field.
<h:inputText value="#{user.userName}" required="true">
13
UserBean.java
public class UserBean {
……..
public String login(){
…..
return “login”;
}
public String getName() { . . . }
public void setName(String newValue) {. . . }
public String getPassword() { . . . }
public void setPassword(String newValue) { . . . }
...
}
14
Configuration file (faces-config.xml)
<?xml version="1.0"?>
<faces-config>
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</ navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>com.corejsf.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
15
Configuration File(Cntd.)
• faces-config.xml defines how one page will navigate to next.
Also specifies managed beans.
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</navigation-rule
• <from-view-id> page you are currently on.
• <to-view-id> next page to display.
• <from-outcome> value matches the action attribute of the
command button of index.jsp
<h:commandButton value="Login" action="login"/>
16
Configuration file (Cntd.)
• Managed bean is the model of the framework.
• <managed-bean-name> is the name the views use to
reference the bean.<managed-bean-name>user</managed-bean-name>
<h:inputText value="#{user.name}“ required=“true”/>
<managed-bean-scope>session</managed-bean-scope>
17
Web.xml (Deployment Descriptor)
<context-param>
<param-name>
javax.faces.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/faces-config.xml
</param-value>
<description>
</description>
</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>
18
Web.xml (Cntd.)
• Javax.faces.CONFIG_FILES parameter tells where the JSF configuration file
exists.
<param-name>
javax.faces.CONFIG_FILES
</param-name>
<param-value>
/WEB-INF/examples-config.xml
</param-value>
• Javax.faces.STATE_SAVING_METHOD specifies where the state must be
saved: client or server.
<param-name>
javax.faces.STATE_SAVING_METHOD
</param-name>
<param-value>server</param-value>
• The servlet-mapping and servlet blocks specify that any URL that ends in
a .jsf extension should be redirected through a servlet called
javax.faces.webapp.FacesServlet.
19
Life cycle of JSF
Questions?
JSF Tags
• JSF application typically uses JSP pages to represent views. JSF provides useful
special tags to enhance these views. Each tag gives rise to an associated
component. JSF provides 43 tags in two standard JSF tag libraries:
• JSF Core Tags Library and
• JSF Html Tags Library
• Even a very simple page uses tags from both libraries.
• <%@ taglib uri=”http://java.sun.com/jsf/core “ prefix=”f” %>
<%@ taglib uri=”http://java.sun.com/jsf/html “ prefix=”h” %>
<f:view>
<h:form>
……………
……………
</h:form>
</f:view>
What is Apache MyFaces?
• First free open source implementation of JSF.
• Provides rich set of prefabricated components.
• Tomahawk
• Original MyFaces component library.
• Tobago
• Apache Library now under MyFaces umbrella.
• Trinidad
• Originally Oracle ADF components.
23
JSF Tags
• JSF HTML Tag Reference
html tags provided in JSF.
• JSF column Tag
Used for creating columns of a table. This tag creates a data column inside
a data table.
<h:dataTable border="1">
<f:facet name="header">
<h:outputText value="This is header."/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Student"/>
</f:facet>
</h:column>
• JSF commandButton Tag
This tag renders an HTML submit button. This button can be associated
with bean.
• <h:commandButton image="/unprotected/images/buttons/finish.JPG"
id="pmsfinishbutton" value="Finish" title="FINISH" type=""
action="#{Navigation.next}" onclick="return
submitdisableButton('pmsfinishbutton');" />
• JSF commandLink Tag
JSF commandLink tag which is rendered as a anchor tag.
• <h:commandLink value="Modify Existing Ticker Items" style="color:
red" action="#{TickerHelperBean.allTickerResponse}"/>
• JSF dataTable Tag
This tag is used to create table on the page. The component is
rendered as an html <table> element.
• JSF form Tag
This tag renders html form element which contains the data that is
submitted with the form. This tag uses "POST" method.
<h:form id="tvhardware">
</h:form>
• JSF graphicImage Tag
This displays the image on the page. This tag renders an html "img" element.
• <t:graphicImage value="/unprotected/images/content_heading_arrow.jpg"
width="19" height="33"/>
This is used to display the element that enables the user to select only one
among the list of available options.
<t:selectOneMenu id ="noofsignatories"
value="#{orderCapture.customerDetailsHelper.numberOfSignatories}" >
<a4j:support event="onchange" reRender="signatories"
ajaxSingle="true" />
<f:selectItem id="selectitem1" itemLabel="1"
itemValue="1"></f:selectItem></t:selectOneMenu>
JSF selectOneRadio Tag
This allows the user to select one option from a set of available
options.
<h:selectOneRadio id="activeProfile"
value="#{TariffLinkManaged.selectedProfile}" styleClass="labels"
layout="lineDirection" >
<f:selectItems id="selectedProfile"
value="#{TariffLinkManaged.profileOptions}"
/>
</h:selectOneRadio>
All JSF Core Tags:
f :view Creates the top-level view
f:subview Creates a subview of a view
<f:view>
<t:panelLayout id="page" layout="classic" width="1000" cellpadding="0"
border="0" align="center" bodyClass="panel_body"
navigationClass="panel_leftnav" >
<f:facet name="header">
<f:subview id="header">
<%@ include file="/protected/subpages/header.jsp"%>
</f:subview>
</f:facet>
<f:facet name="navigation">
<f:subview id="menu">
<%@ include file="/protected/subpages/leftShoppingCart.jsp"%>
</f:subview>
</f:facet>
<f:facet name="body">
<f:subview id="body1" rendered="true">
<%@ include
file="/protected/additionalorderitems/subpages/sub_activatemaliciouscalltr
acing.jsp"%>
</f:subview>
</f:facet>
<f:facet
name="footer">
<f:subview
id="footer">
<%@ include file="/protected/subpages/footer.jsp"%>
</f:subview>
</f:facet>
</t:panelLayout>
</f:view>
• f:param Constructs a parameter component
• <t:commandLink value="Modify discount schemes" type="submit"
action="#{organisationManagementMB.modifyOrganisationDiscounts}"
styleClass="black_link" >
• <f:param name="selectedOrganisationForModification"
value="#{record.organisationId}" />
• </t:commandLink>
•
public void processValueChange(ValueChangeEvent ce){
}
• f:valueChangeListener Adds a valuechange listener to a component
• f:validator Adds a validator to a component
• <h:inputText id="email" required="true">
<f:validator validatorId="checkvalidemail" />
</h:inputText>
• f:validateDoubleRange Validates a double range for a component’s value
• f:validateLength Validates the length of a component’s value
• <h:inputSecret id="PWD" value="#{MessageBean.b}" required="true" >
<f:validateLength maximum="15" minimum="6"/>
</h:inputSecret>
• f:validateLongRange Validates a long range for a component’s value
• f:facet Adds a facet to a component
• f:loadBundle Loads a resource bundle, stores properties as a Map
• <f:loadBundle basename="RB" var="mes"/>
<f:view>
<html>
<body>
<h:form>
<h:outputText value="#{mes.greeting_text}" />
</h:form>
• f:selectitems Specifies items for a select one or select many component
• f:selectitem Specifies an item for a select one or select many component
• f:verbatim Adds markup to a JSF page
Rich Faces
• “RichFaces is a rich component library for
• JSF and an advanced framework for
• easily integrating AJAX capabilities into
• business application development.”
• which really means.....
• I don't NEED to know JavaScript.
• JavaServer Faces
• +
• AJAX
• =
• JBoss RichFaces
• Rich JSF Components
• A framework designed to add Ajax-functionality to
• existing JSF solutions.
• • JSF tags are augmented with additional RichFaces
tags
• to provide this special functionality.
<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax"
prefix="a4j"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<head>
<title>Repeater </title>
</head>
<body>
<f:view>
<h:form>
<h:inputText size="50" value="#{bean.text}" >
<a4j:support event="onkeyup" reRender="rep"/>
</h:inputText>
<h:outputText value="#{bean.text}" id="rep"/>
</h:form>
</f:view>
</body>
</html>
• package demo;
• public class Bean {
• private String text;
• public Bean() {}
• public void setText(String text) {
• this.text = text;
• }
• public String getText() {
• return text;
• }
• }
• RichFaces has three tags used to fire an Ajax request.
• – <a4j:commandButton>
• – <a4j:commandLink>
• – <a4j:support>
• • The two first are used to render a button and a link,
• respectively, with Ajax-functionality. The support tag is
• used to add functionality to an existing component.
• – AjaxCommandButton: renders a button for submitting a
form.
• – AjaxCommandLink: renders a link for submitting a form.
• – AjaxCommandSupport: delivers Ajax support for existing
• elements (such as e.g. input fields).
By using attributes on the Action Components, it is possible to
control how much is sent with the request – and what is
updated
by the response:
– ajaxSingle: this attribute defines that only that specific
component is sent with the request.
– reRender: a comma separated list of components to be
rendered from the response.
<h:form>
<h:inputText value="#{person.name}" >
<a4j:support event="onkeyup" reRender="test"
ajaxSingle="true"/>
</h:inputText>
<h:inputText value="#{person.middleName}"/>
It is possible to integrate custom JavaScript with these components
using these two attributes:
– onsubmit: JavaScript code to execute before the form is sent (e.g. for
checking request parameters client side).
– oncomplete: JavaScript code to execute after the Ajax response has
returned (e.g. for post-processing the response).
<a4j:outputPanel id="panel">
<h:form>
<h:selectOneMenu value="#{bean.text}">
<f:selectItem itemValue="Danmark" itemLabel="Danmark"/>
<f:selectItem itemValue="Norge" itemLabel="Norge"/>
<f:selectItem itemValue="Sverige" itemLabel="Sverige"/>
<a4j:support event="onchange" reRender="panel"
onsubmit="if(!confirm(’Are you sure that you want to switch country?'))
{form.reset(); return false;}"
oncomplete="alert(’The value was saved server-side!')"/>
</h:selectOneMenu>
<br/>
<h:outputText value="#{bean.text}"/>
• In general, data being sent in a RichFaces request will be
delimited by a form tag (<a4j:form> or <h:form>).
• When the server receives the request, the contents of it
will be decoded by the Faces servlet, which leads the JSF
component tree to be updated. Then the response is sent
back to the client through the RichFaces renderkit.
• The decode process, however, does take up a reasonable
amount of resources. The tag <a4j:region> is useful for
delimiting the number of components to decode,
reducing the performance hit.
• Note that the entire contents of the form is still sent in
the request (and received in the response) – but only the
region is processed.
Output Components
• RichFaces offers certain components to
render output.
• These components are output panels
Output panels ”ajaxify” a part of the page and makes this part
sensitive to changes in the surrounding Ajax Container (region or
view root).
• Transient contents (raw HTML or the JSF <verbatim> tag), which
usually is not saved in the component tree, will be added to the
tree anyway for quick access.
• The tag <a4j:outputPanel> is used for this – or the class
HtmlAjaxOutputPanel.
• The tag generated a <span> or <div> tag in the client – depending
on the value of the attribute layout.
Status indicator for Ajax requests
• With the tag <a4j:status> the user can be notified of the state of a current Ajax
request.
• Programmatically, the class HTMLAjaxStatus is used:
• The element has attributes representing text and style to be shown at start (Ajax
transfer
in progress) and stop (no Ajax request being processed currently), respectively – these
are named startText and stopText. Alternatively, JSF facets provide the same effect:
<a4j:status startText="Progress" stopText="Done" for="stat1">
<a4j:status for="stat2">
<f:facet name="start">
<h:graphicImage value="ajax_process.gif" />
</f:facet>
<f:facet name="stop">
<h:graphicImage value="ajax_stoped.gif" />
</f:facet>
</a4j:status
Custom Components
• Extend a UIComponent
– Create a class that extends UIComponent
– Save the component state
– Register the component with faces-config.xml
• Define the renderer or implement inline
– Override encode
– Override decode
– Register the renderer with faces-config.xml
• Create a custom tag that subclasses UIComponentTag
– Return the renderer type
– Return the component type
– Set up properties that might use JSF expressions
• import java.io.IOException; import
javax.faces.component.UIOutput; import
javax.faces.context.FacesContext; import
javax.faces.context.ResponseWriter;
• public class LabelComponent extends
UIOutput{ private String label; public String
getLabel() { return label; } public void
setLabel(String label) { this.label = label; } ...
• @Override public Object saveState(FacesContext
context) { Object values[] = new Object[2];
values[0] = super.saveState(context); values[1] =
label; return ((Object) (values)); }
• @Override public void restoreState(FacesContext
context, Object state) { Object values[] =
(Object[])state; super.restoreState(context,
values[0]); label = (String)values[1]; }
• <faces-config> <component> <component-
type>simple.Label</component-type>
<component-class>
arcmind.simple.LabelComponent
</component-class> </component>
• public class LabelComponent extends
UIOutput{ ... public void
encodeBegin(FacesContext context) throws
IOException { ResponseWriter writer =
context.getResponseWriter();
writer.startElement("label", this);
writer.write(label); writer.endElement("label");
writer.flush(); } ... }
• public class LabelComponent extends
UIOutput{ ... public String getFamily(){ return
"simple.Label"; } ... }