zongwei yuan 1. why javaserver faces model-view-controller (mvc) architecture easy to drop...

28
JavaServer Faces(JSF) and RBAC Web Application Zongwei Yuan 1

Upload: miranda-sterry

Post on 14-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

1

JavaServer Faces(JSF) and RBAC Web Application

Zongwei Yuan

2

Why JavaServer FacesModel-view-controller (MVC) architectureEasy 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

3

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>

4

Managed beanDefinitionBean Properties

T getFoo() void setFoo(T newValue)

Value binding expression <h:outputText value="#{user.name}"/>

Bean scope Request Session application

Backing beans

5

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)

6

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

7

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

8

NavigationNavigation 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>

9

Load Property Bundle<f:loadBundle basename="bundle.messages" var="msg"/><h:outputText value="#{msg.inputname_header}"/> localization

10

Standard JSF TagsCore 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>

11

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 validateDoubleRangeValidates 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

12

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

13

Tag Attribute

Shared, unique, converter, validator, valuesHtml and dhtml event attributeAction and actionListenerRendering and style

14

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>

15

h:formHas most of HTML and DHTML event attributesHas no method and action

Use only post methodNavigation submitted by components

Works with JavaScript

16

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>

17

Buttons and linksAction and actionListener attributeImmediate attribute

18

Message tag

<h:message> and <h:mesages>Some special attributes:

globalOnlyforshowDetailerrorClass

Information Warning Error fatal

19

Data table (1)1. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>2. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>3. <html>4. <f:view>5. <head>6. <f:loadBundle basename="com.corejsf.messages" var="msgs"/>7. <title>8. <h:outputText value="#{msgs.windowTitle}"/>9. </title>10. </head>11. <body>12. <h:outputText value="#{msgs.pageTitle}"/>13. <p>14. <h:form>15. 16. <h:dataTable value="#{tableData.names}” var="name">17. <h:column>18. <h:outputText value="#{name.last}"/>19. <f:verbatim>,</f:verbatim>20. </h:column>21. <h:column>22. <h:outputText value="#{name.first}"/>23. </h:column>24. </h:dataTable>

25. </h:form>26. </body>27. </f:view>28. </html>

20

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

21

Conversion and ValidationStandard 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"/>

22

Using standard validatorsBuilt-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” attributeBypass validation

<h:commandButton value="Cancel" action="cancel" immediate="true"/>

23

Converter Object getAsObject(FacesContext context, UIComponent component, String newValue)

String getAsString(FacesContext context, UIComponent component, Object value)

ValidatorImplement interface javax.faces.validator.Validator

Register in configure.xmlValidate 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) {

...

}

}

Implement custom converter and validator

24

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)

25

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); }}

26

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)

27

MyFaces projectIntroduction

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 deploymenthttp://myfaces.apache.org/gettingstarted.html http://www.irian.at/myfaces/

Facelets Template, composite component

28

RBAC web app on MyFacesDatabase access applicationUser ViewSource code example

http://www-bd.fnal.gov/rbac/inputname.jsf