280 likes | 381 Views
JavaServer Faces(JSF) and RBAC Web Application. Zongwei Yuan. Why JavaServer Faces. Model-view-controller (MVC) architecture Easy to Drop components onto a web page by adding component tags. Bind components on a page to server-side data.
E N D
JavaServer Faces(JSF) and RBAC Web Application Zongwei Yuan
Why JavaServer Faces • Model-view-controller (MVC) architecture • Easy to • Drop components onto a web page by adding component tags. • Bind components on a page to server-side data. • Wire component-generated events to server-side application code. • Save and restore application state beyond the life of server requests. • Reuse and extend components through customization. • Provide important services: • Data conversion • Validation and error handling • Internationalization • Custom component • Alternative render • Tool support • Extensibility • Install JSF • Jsf-api.jar , jsf-impl.jar and jstl.jar
Sample JSF File index.jsp 1. <html> 2. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 3. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 4. <f:view> 6. <head> <title>A Simple JavaServer Faces Application</title> </head> 9. <body> 10. <h:form> 11. <h3>Please enter your name and password.</h3> 12. <table> 13. <tr> 14. <td>Name:</td> 15. <td><h:inputText value="#{user.name}"/> </td> 16. </tr> 17. <tr> 18. <td>Password:</td> 19. <td><h:inputSecret value="#{user.password}"/> </td> 20. </tr> 21. </table> 22. <p> <h:commandButton value="Login" action="login"/> </p> 25. </h:form> 26. </body> 27. </f:view> 28. </html>
Managed bean • Definition • Bean Properties • T getFoo() • void setFoo(T newValue) • Value binding expression • <h:outputText value="#{user.name}"/> • Bean scope • Request • Session • application • Backing beans
Configure Beans • WEB-INF/web.xml <web-app> <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value>WEB-INF/navigation.xml,WEB-INF/faces-configure.xml</param-value> </context-param> ... </web-app> • WEB-INF/faces-configure.xml <faces-config> <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> • In faces-configure.xml we can setting property values initializing lists and maps collection. changing bean definitions (for backing bean) string conversions (convert text value to different data type)
Value Binding expressions (1) • Value binding • <h:inputText rendered="#{!bean.hide}" ... /> • Reference to implicit objects • header • headerValues • param • paramValues • cookie • initParam • requestScope • sessionScope • applicationScope • facesContext • view
Value binding expressions (2) • Immediate and deferred evaluation expression (${ } and #{ }) • Composite expressions: • arithmetic operators + - * / % • relational operators < <= > >= == != • logical operators && || ! • the “empty”, “not” operator. • the ternary ?: selection operator • Method binding • <h:commandButton action="#{user.checkPassword}"/> • Attributes can bind to method: • action • validator • actionListener • valueChangeListener
Navigation • Navigation rules • In JSF file: • <h:commandButton label="Login" action="login"/> • In faces-configure.xml: • <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> • Dynamic navigation • <h:commandButton label="Login“ action="#{loginController.verifyUser}"/> • <from-action>#{quiz.answerAction}</from-action>
Load Property Bundle • <f:loadBundle basename="bundle.messages" var="msg"/> • <h:outputText value="#{msg.inputname_header}"/> • localization
Standard JSF Tags • Core library tag total 18 • <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> • HTML library tag total 25 • <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> • Such as: <f:view> <h:form> ... </h:form> </f:view>
Core Tags • view Creates the top-level view • subview Creates a subview of a view • facet Adds a facet to a component • attribute Adds an attribute (key/value) to a component • param Adds a parameter to a component • actionListener Adds an action listener to a component • valueChangeListener Adds a valuechange listener to a component • converter Adds an arbitrary converter to a component • convertDateTime Adds a datetime converter to a component • convertNumber Adds a number converter to a component • validator Adds a validator to a component • validateDoubleRange Validates a double range for a component's value • validateLength Validates the length of a component's value • validateLongRange Validates a long range for a component's value • loadBundle Loads a resource bundle, stores properties as a Map • selectitems Specifies items for a select one or select many component • selectitem Specifies an item for a select one or select many component • verbatim Adds markup to a JSF page
HTML Tags • form HTML form • inputText Single-line text input control • inputTextarea Multiline text input control • inputSecret Password input control • inputHidden Hidden field • outputLabel Label for another component for accessibility • outputLink HTML anchor • outputFormat Like outputText, but formats compound messages • outputText Single-line text output • commandButton Button: submit, reset, or pushbutton • commandLink Link that acts like a pushbutton • message Displays the most recent message for a component • messages Displays all messages • graphicImage Displays an image • selectOneListbox Single-select listbox • selectOneMenu Single-select menu • selectOneRadio Set of radio buttons • selectBooleanCheckbox Checkbox • selectManyCheckbox Set of checkboxes • selectManyListbox Multiselect listbox • selectManyMenu Multiselect menu • panelGrid HTML table • panelGroup Two or more components that are laid out as one • dataTable A feature-rich table control • column Column in a dataTable
Tag Attribute • Shared, unique, • converter, validator, values • Html and dhtml event attribute • Action and actionListener • Rendering and style
JSTL tags • Reference • <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> • <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> • Tags • Core • Functions • Database • XML • I18N (format) • Examples • <x:choose> • <sql:update> • <c:if> • <c:out> • <c:set>
h:form • Has most of HTML and DHTML event attributes • Has no method and action • Use only post method • Navigation submitted by components • Works with JavaScript
Textfield and Textarea • immediate, required, redisplay attribute • <h:outputFormat> <h:outputFormat value="{0} is {1} years old"> <f:param value=“Tom"/> <f:param value="38"/> </h:outputFormat>
Buttons and links • Action and actionListener attribute • Immediate attribute
Message tag • <h:message> and <h:mesages> • Some special attributes: • globalOnly • for • showDetail • errorClass • Information • Warning • Error • fatal
Data table (1) • <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> • <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> • <html> • <f:view> • <head> • <f:loadBundle basename="com.corejsf.messages" var="msgs"/> • <title> • <h:outputText value="#{msgs.windowTitle}"/> • </title> • </head> • <body> • <h:outputText value="#{msgs.pageTitle}"/> • <p> • <h:form> • <h:dataTable value="#{tableData.names}” var="name"> • <h:column> • <h:outputText value="#{name.last}"/> • <f:verbatim>,</f:verbatim> • </h:column> • <h:column> • <h:outputText value="#{name.first}"/> • </h:column> • </h:dataTable> • </h:form> • </body> • </f:view> • </html>
Data table (2) • Data – one of follow types: • Array ArrayDataModel • java.util.List ListDataModel • java.sql.ResultSet ResultDataModel • javax.servlet.jsp.jstl.sql.Result ResultSetDataModel • javax.faces.model.DataModel ScalarDataModel • Header and footer facet <h:column> <f:facet name="header"> <%-- header components go here --%> </f:facet> </h:column> • Scrolling • scroll bar. use <div> • pageant. use page widget
Conversion and Validation • Standard Conversion tag • <f:convertNumber> • <f:convertDateTime> <h:inputText value="#{payment.amount}"> <f:convertNumber minFractionDigits="2"/> </h:inputText> • Use converter attribute • <h:outputText value="#{payment.date}" converter="javax.faces.DateTime"/>
Using standard validators • Built-in validation • Checking the length of a string • Checking limits for a numerical value • Checking that a value has been supplied • Validation tag • f:validateDoubleRange • f:validateLongRange • f:validateLength • Overwrite messages • create your own message bundle property • overwrite message property value on the same key • update configure.xml file to load the new bundle • “required” attribute • Bypass validation • <h:commandButton value="Cancel" action="cancel" immediate="true"/>
Implement custom converter and validator • Converter • Object getAsObject(FacesContext context, UIComponent component, String newValue) String getAsString(FacesContext context, UIComponent component, Object value) • Validator • Implement interface javax.faces.validator.Validator • Register in configure.xml • Validate with bean method • <h:inputText id="card" value="#{payment.card}" required="true" validator="#{payment.luhnCheck}"/> • public class PaymentBean { ... public void luhnCheck(FacesContext context, UIComponent component, Object value) { ... } }
Event Handling (1) • JSF support 3 kind events: • value change events • action events • phase events • Request life cycle • Restore View • Apply Request Values • Process Validations • Update Model Values • Invoke Application • Render Response • action an actionListener attribute • ActionListener – for user interfaces logic and interface info (first) • Action – for business logic (second triggered)
Event Handling (2) • Use action listener tag • f:actionListener and f:valueChangeListener <h:selectOneMenu value="#{form.country}" onchange="submit()"> <f:valueChangeListener type="com.corejsf.CountryListener"/> <f:selectItems value="#{form.countryNames}"/> </h:selectOneMenu> • Listener implements public class CountryListener implements ValueChangeListener { private static final String US = "United States"; public void processValueChange(ValueChangeEvent event) { FacesContext context = FacesContext.getCurrentInstance(); if (US.equals((String) event.getNewValue())) context.getViewRoot().setLocale(Locale.US); else context.getViewRoot().setLocale(Locale.CANADA); } }
Event Handling (3) • “immediate” to bypass other component validation • Add immediate attribute • Calling FacesContext.renderResponse() • Phase event listener • In configure.xml <faces-config> <lifecycle> <phase-listener>com.corejsf.PhaseTracker</phase-listener> </lifecycle> </faces-config> • Listener implements interface javax.faces.event.PhaseListener • PhaseId getPhaseId() • void afterPhase(PhaseEvent) • void beforePhase(PhaseEvent)
MyFaces project • Introduction • Compatible with tomcat and easy to deploy • Rich debugging and diagnostic info • Rich components (pagination) • Provide eclipse plug-in • Sub project • Tomahawk • Trinidad • ExtVal (Extensions Validator) • Installation and deployment • http://myfaces.apache.org/gettingstarted.html • http://www.irian.at/myfaces/ • Facelets • Template, composite component
RBAC web app on MyFaces • Database access application • User View • Source code example • http://www-bd.fnal.gov/rbac/inputname.jsf