SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Vinay Kumar
 JSF Introduction
 Page Navigation
 Managed Beans
 Expression Language
 Properties File
 Event Handling
 HTML Library
 Validation
 JDBC in JSF
 Data Tables
 Ajax-4-JSF
 Basic component tags
 Advanced custom tags
 Custom components
Different views of JSF
Comparing JSF to standard servlet/JSP technology
Comparing JSF to Apache Struts
A set of Web-based GUI controls and associated handlers?
– JSF provides many prebuilt HTML-oriented GUI controls, along
with code to handle their events.
A device-independent GUI control framework?
– JSF can be used to generate graphics in formats other than HTML,
using protocols other than HTTP.
A better Struts?
– Like Apache Struts, JSF can be viewed as an MVC framework for
building HTML forms, validating their values, invoking business
logic, and displaying results.
• Custom GUI controls
– JSF provides a set of APIs and associated custom tags to create
HTML forms that have complex interfaces
• Event handling
– JSF makes it easy to designate Java code that is invoked when forms
are submitted. The code can respond to particular buttons, changes in
particular values, certain user selections, and so on.
• Managed beans
– In JSP, you can use property="*" with jsp:setProperty to
automatically populate a bean based on request parameters. JSF
extends this capability and adds in several utilities, all of which serve
to greatly simplify request param processing.
• Expression Language
– JSF provides a concise and powerful language for accessing bean
properties and collection elements
• Bigger learning curve
– To use MVC with the standard RequestDispatcher, you need to be
comfortable with the standard JSP and servlet APIs. To use MVC with
JSF, you have to be comfortable with the standard JSP and servlet APIs
and a large and elaborate framework that is almost equal in size to the
core system. This drawback is especially significant with smaller
projects, near-term deadlines, and less experienced developers; you
could spend as much time learning JSF as building your actual system.
• Worse documentation
– Compared to the standard servlet and JSP APIs, JSF has fewer online
resources, and many first-time users find the online JSF
documentation confusing and poorly organized. MyFaces is
particularly bad.
Static Navigation
• When form submitted
– A static page is displayed
• Static result
– No business logic, beans, or Java code of any sort
– The return path is specified in the button itself.
• Main points
– Format of original form
– Use of navigation-rule in faces-config.xml
• Input form has following format:
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
HTML markup
<h:form>
HTML markup and h:blah tags
</h:form>
HTML markup
</f:view>

• faces-config.xml specifies navigation rules:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC …>
<faces-config>
<navigation-rule>
<from-view-id>/blah.jsp</from-view-id>
<navigation-case>
<from-outcome>some string</from-outcome>
<to-view-id>/WEB-INF/results/something.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
The h:form element
– ACTION is automatically self (current URL)
– METHOD is automatically POST
• Elements inside h:form
– Use special tags to represent input elements

• h:inputText corresponds to <INPUT TYPE="TEXT">
• h:inputSecret corresponds to <INPUT TYPE="PASSWORD">
• h:commandButton corresponds to <INPUT TYPE="SUBMIT">

– In later sections, we will see that input elements will be associated
with bean properties
– For static navigation, specify simple string as action of
h:commandButton
• String must match navigation rule from faces-config.xml
register.jsp

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE …>
<HTML>
<HEAD>…</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">New Account Registration</TH></TR>
</TABLE>
<P>
<h:form>
Email address: <h:inputText/><BR>
Password: <h:inputSecret/><BR>
<h:commandButton value="Sign Me Up!" action="register"/>
</h:form>
</CENTER></BODY></HTML>
</f:view>
Result – resigter.jsp
• General format

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC …>
<faces-config>
…
</faces-config>

• Specifying the navigation rules

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC …>
<faces-config>
<navigation-rule>
<from-view-id>/register.jsp</from-view-id>
<navigation-case>
<from-outcome>register</from-outcome>
<to-view-id>/WEB-INF/results/result.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
RequestDispatcher.forward used
– So page can/should be in WEB-INF

• Example code:

– …/WEB-INF/results/result.jsp
<!DOCTYPE …>
<HTML>
<HEAD>…</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">Success</TH></TR>
</TABLE>
<H2>You have registered successfully.</H2>
</CENTER>
</BODY></HTML>
Note that the URL is unchanged
Filename/URL correspondence

– Actual files are of the form blah.jsp
– URLs used are of the form blah.faces
– You must prevent clients from directly accessing JSP
pages
• Since they would give erroneous results

• Strategies

– You cannot put input-form JSP pages in WEB-INF
• Because URL must correspond directly to file location
– So, use filter in web.xml. But:
• You have to know the extension (.faces)
• Assumes no non-JSF .jsp pages

• This is a major drawback to JSF design
FacesRedirectFilter
public class FacesRedirectFilter implements Filter {
private final static String EXTENSION = "faces";
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
String uri = request.getRequestURI();
if (uri.endsWith(".jsp")) {
int length = uri.length();
String newAddress =
uri.substring(0, length-3) + EXTENSION;
response.sendRedirect(newAddress);
} else { // Address ended in "/"
response.sendRedirect("index.faces");
}
}
<filter>
<filter-name>faces-redirect-filter</filter-name>
<filter-class>
coreservlets.FacesRedirectFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>faces-redirect-filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
Dynamic Navigation
• A form is displayed

– Form uses f:view and h:form

• The form is submitted to itself

– Original URL and ACTION URL are http://…/blah.faces

• A bean is instantiated

– Listed in the managed-bean section of faces-config.xml

• The action controller method is invoked

– Listed in the action attribute of h:commandButton

• The action method returns a condition

– A string that matches from-outcome in the navigation rules in facesconfig.xml

• A results page is displayed

– The page is specified by to-view-id in the navigation rules in facesconfig.xml
1) Create a bean

A) Properties for form data
B) Action controller method
C) Placeholders for results data

2) Create an input form

A) Input fields refer to bean properties
B) Button specifies action controller method that will return condition

3) Edit faces-config.xml

A) Declare the bean
B) Specify navigation rules

4) Create results pages

– Output form data and results data with h:outputText

5) Prevent direct access to JSP pages

– Use a filter that redirects blah.jsp to blah.faces
• Collects info to see if user qualifies for health
plan
• When form submitted, one of two possible
results will be displayed
– User is accepted into health plan
– User is rejected from health plan

• Main points

– Specifying an action controller in the form
– Creating an action controller method in the bean
– Using faces-config.xml to
• Declare bean
• Map return conditions to output pages
• Specify the controller with #{beanName.methodName}
<h:commandButton
value="Sign Me Up!"
action="#{healthPlanController.signup}"/>

• Controller method returns strings corresponding to conditions
– If null is returned, the form is redisplayed
– Unlike with Struts, the controller need not extend a special class

• Use faces-config.xml to declare the controller as follows

<faces-config>
<managed-bean>
<managed-bean-name>controller name</managed-bean-name>
<managed-bean-class>controller class</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>

• Add multiple navigation-rule entries to faces-config.xml
– One for each possible string returned by the controller
– If no string matches, the form is redisplayed
(A) Properties for form data
– Postponed until next session

(B) Action controller method

public class HealthPlanController {
public String signup() {
if (Math.random() < 0.2) {
return("accepted");
} else {
return("rejected");
}
}
}

(C) Placeholders for results data
– Postponed until next session
• Same general syntax as in previous example
– Except for action of commandButton

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
…
<h:form>
First name: <h:inputText/><BR>
Last name: <h:inputText/><BR>
...
<h:commandButton
value="Sign Me Up!"
action="#{healthPlanController.signup}"/>
</h:form>…
</f:view>
(A) Declaring the bean
…
<faces-config>
<managed-bean>
<managed-bean-name>
healthPlanController
</managed-bean-name>
<managed-bean-class>
coreservlets.HealthPlanController
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
…
</faces-config>
(B) Specifying navigation rules

– Outcomes should match return values of controller

<faces-config>
… (bean definitions
from previous page)
<navigation-rule>
<from-view-id>/signup.jsp</from-view-id>
<navigation-case>
<from-outcome>accepted</from-outcome>
<to-view-id>/WEB-INF/results/accepted.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>rejected</from-outcome>
<to-view-id>/WEB-INF/results/rejected.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
• …/WEB-INF/results/accepted.jsp
<!DOCTYPE …>
<HTML>
<HEAD>…</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">Accepted!</TH></TR>
</TABLE>
<H2>You are accepted into our health plan.</H2>
Congratulations.
</CENTER>
</BODY></HTML>
…/WEB-INF/results/accepted.jsp
<!DOCTYPE …>
<HTML>
<HEAD>…</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">Accepted!</TH></TR>
</TABLE>
<H2>You are accepted into our health plan.</H2>
Congratulations.
</CENTER>
</BODY></HTML>
…/WEB-INF/results/rejected.jsp
<!DOCTYPE …>
<HTML>
<HEAD>…</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">Rejected!</TH></TR>
</TABLE>
<H2>You are rejected from our health plan.</H2>
Get lost.
</CENTER>
</BODY></HTML>
• Use filter that captures url-pattern *.jsp
– No changes from previous example
• Wildcards in navigation rule

– * for from-view-id matches any starting page

<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/WEB-INF/results/success.jsp</to-view-id>
</navigation-case>
</navigation-rule>

• Getting the request and response objects

HttpServletRequest request =
(HttpServletRequest)context.getRequest();
HttpServletResponse response =
(HttpServletResponse)context.getResponse();

• In some environments, you cast results of getRequest and getResponse
to values other than HttpServletRequest and HttpServletResponse
E.g., in a portlet environment, you might cast result to
PortletRequest and PortletResponse
• If you have several different addresses in
your app, it is OK to alternate
<managed-bean>
Stuff for bean1
</managed-bean>
<navigation-rule>
Rules for address that uses bean1
</navigation-rule>
<managed-bean>
Stuff for bean2
</managed-bean>
<navigation-rule>
Rules for address that uses bean2
</navigation-rule>

– Of course, it is also OK to put all bean defs at the top,
followed by all navigation rules.
• Using beans to represent request
parameters
• Declaring beans in faces-config.xml
• Referring to beans in input forms
• Outputting bean properties
1) Create a bean

A) Properties for form data
B) Action controller method
C) Placeholders for results data

2) Create an input form

A) Input fields refer to bean properties
B) Button specifies action controller method that will return condition

3) Edit faces-config.xml

A) Declare the bean
B) Specify navigation rules

4) Create results pages

– Output form data and results data with h:outputText

5) Prevent direct access to JSP pages

– Use a filter that redirects blah.jsp to blah.faces
• When form submitted, three possible results
– Error message re illegal email address
– Error message re illegal password
– Success

• New features
– Action controller obtains request data from within bean
– Output pages access bean properties

• Main points
– Defining a bean with properties for the form data
– Declaring beans in faces-config.xml
– Outputting bean properties
(1A) Form data

public class RegistrationBean implements Serializable {
private String email = "user@host";
private String password = "";
public String getEmail() {
return(email);
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return(password);
}
public void setPassword(String password) {
this.password = password;
}
(1B) Action controller method

public String register() {
if ((email == null) ||
(email.trim().length() < 3) ||
(email.indexOf("@") == -1)) {
suggestion = SuggestionUtils.getSuggestionBean();
return("bad-address");
} else if ((password == null) ||
(password.trim().length() < 6)) {
suggestion = SuggestionUtils.getSuggestionBean();
return("bad-password");
} else {
return("success");
}
}
(1C) Placeholder for storing results
– Note that action controller method called business
logic and placed the result in this placeholder
private SuggestionBean suggestion;
public SuggestionBean getSuggestion() {
return(suggestion);
}
Result returned by business logic

package coreservlets;
import java.io.*;
public class SuggestionBean implements Serializable {
private String email;
private String password;
public SuggestionBean(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return(email);
}
public String getPassword() {
return(password);
}
}
• Business logic

public class SuggestionUtils {
private static String[] suggestedAddresses =
{ "president@whitehouse.gov",
"gates@microsoft.com",
“tennyson@google.com",
“s.jobes@apple.com" };
private static String chars =
"abcdefghijklmnopqrstuvwxyz0123456789#@$%^&*?!";
public static SuggestionBean getSuggestionBean() {
String address = randomString(suggestedAddresses);
String password = randomString(chars, 8);
return(new SuggestionBean(address, password));
}
...
}
• Similar to previous example, except

– h:inputBlah tags given a value attribute identifying the corresponding bean
property

• Example code

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>…
<h:form>
Email address:
<h:inputText value="#{registrationBean.email}"/><BR>
Password:
<h:inputSecret value="#{registrationBean.password}"/><BR>
<h:commandButton value="Sign Me Up!"
action="#{registrationBean.register}"/>
</h:form>…
</f:view>
The user@host value comes from the bean
(A) Declare bean
…
<faces-config>
<managed-bean>
<managed-bean-name>
registrationBean
</managed-bean-name>
<managed-bean-class>
coreservlets.RegistrationBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
…
</faces-config>
• (B) Define navigation rules

…
<faces-config>
…
<navigation-rule>
<from-view-id>/register.jsp</from-view-id>
<navigation-case>
<from-outcome>bad-address</from-outcome>
<to-view-id>/WEB-INF/results/bad-address.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>bad-password</from-outcome>
<to-view-id>/WEB-INF/results/bad-password.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/WEB-INF/results/success.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
• …/jsf-beans/WEB-INF/results/bad-address.jsp
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE …>
<HTML>
…
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">Illegal Email Address</TH></TR>
</TABLE>
<P>
The address
"<h:outputText value="#{registrationBean.email}"/>"
is not of the form username@hostname (e.g.,
<h:outputText
value="#{registrationBean.suggestion.email}"/>).
<P>
Please <A HREF="register.faces">try again</A>.
…
</HTML>
</f:view>
Input
Output
• Use filter that captures url-pattern *.jsp
– No changes from previous example
Important
• Shorthand notation for bean properties.
– To reference the companyName property (i.e., result of the
getCompanyName method) of a scoped variable (i.e. object stored in
request, session, or application scope) or managed bean named
company, you use #{company.companyName}. To reference the
firstName property of the president property of a scoped variable or
managed bean named company, you use
#{company.president.firstName}.
• Simple access to collection elements.
– To reference an element of an array, List, or Map, you use
#{variable[indexOrKey]}. Provided that the index or key is in a form
that is legal for Java variable names, the dot notation for beans is
interchangeable with the bracket notation for collections.
Less Important
• Succinct access to request parameters, cookies, and other request data.
– To access the standard types of request data, you can use one of several
predefined implicit objects.
• A small but useful set of simple operators.
– To manipulate objects within EL expressions, you can use any of several
arithmetic, relational, logical, or empty-testing operators.
• Conditional output.
– To choose among output options, you do not have to resort to Java scripting
elements. Instead, you can use #{test ? option1 : option2}.
• Automatic type conversion.
– The expression language removes the need for most typecasts and for much
of the code that parses strings as numbers.
• Empty values instead of error messages.
– In most cases, missing values or
To enforce EL-only with no scripting, use scriptinginvalid in web.xml
– Still permits both the JSF EL and the JSP 2.0 EL
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
version="2.4">
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</web-app>
import java.util.*;
public class TestBean {
private Date creationTime = new Date();
private String greeting = "Hello";
public Date getCreationTime() {
return(creationTime);
}
public String getGreeting() {
return(greeting);
}
public double getRandomNumber() {
return(Math.random());
}
}
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE ...>
<faces-config>
<managed-bean>
<managed-bean-name>testBean</managed-bean-name>
<managed-bean-class>
coreservlets.TestBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
...
</faces-config>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
...
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">Accessing Bean Properties</TH></TR>
</TABLE>
<UL>
<LI>Creation time:
<h:outputText value="#{testBean.creationTime}"/>
<LI>Greeting:
<h:outputText value="#{testBean.greeting}"/>
<LI>Random number:
<h:outputText value="#{testBean.randomNumber}"/>
</UL>
</BODY></HTML>
</f:view>
public class NameBean {
private String firstName = "Missing first name";
private String lastName = "Missing last name";
public NameBean() {}
public NameBean(String firstName, String lastName) {
setFirstName(firstName);
setLastName(lastName);
}
public String getFirstName() {
return(firstName);
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
...
}
public class CompanyBean {
private String companyName;
private String business;
public CompanyBean(String companyName,
String business) {
setCompanyName(companyName);
setBusiness(business);
}
public String getCompanyName() { return(companyName); }
public void setCompanyName(String newCompanyName) {
companyName = newCompanyName;
}
...
}
public class EmployeeBean {
private NameBean name;
private CompanyBean company;
public EmployeeBean(NameBean name, CompanyBean company) {
setName(name);
setCompany(company);
}
public EmployeeBean() {
this(new NameBean("Marty", "Hall"),
new CompanyBean("coreservlets.com",
"J2EE Training and Consulting"));
}
public NameBean getName() { return(name); }
public void setName(NameBean newName) {
name = newName;
}
...
}
<faces-config>
...
<managed-bean>
<managed-bean-name>employee</managed-bean-name>
<managed-bean-class>
coreservlets.EmployeeBean
</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
...
</faces-config>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
...
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">Using Nested Bean Properties</TH></TR>
</TABLE>
<UL>
<LI>Employee's first name:
<h:outputText value="#{employee.name.firstName}"/>
<LI>Employee's last name:
<h:outputText value="#{employee.name.lastName}"/>
<LI>Name of employee's company:
<h:outputText value="#{employee.company.companyName}"/>
<LI>Business area of employee's company:
<h:outputText value="#{employee.company.business}"/>
</UL>
</BODY></HTML>
</f:view>
• Loading properties files
• Simple messages
• Parameterized messages
• Internationalized messages
1. Create a .properties file

• Contains simple keyName=value pairs
• Must be deployed to WEB-INF/classes
• In Eclipse, this means you put it in "src" folder

2. Load file with f:loadBundle

– basename gives base file name
– var gives scoped variable (Map) that will hold results

• Relative to WEB-INF/classes, .properties assumed
• E.g., for WEB-INF/classes/messages.properties
<f:loadBundle basename="messages" var="msgs"/>
• E.g., for WEB-INF/classes/package1/test.properties
<f:loadBundle basename="package1.test" var="msgs"/>

3. Output messages using normal EL
– #{msgs.keyName}
1. Create a .properties file in/under WEB-INF/classes
– Values contain {0}, {1}, {2}, etc.
– E.g., someName=blah {0} blah {1}
– Warning: MyFaces bug prevents single quotes in values

2. Load file with f:loadBundle as before

– basename gives base file name
– var gives scoped variable (Map) that will hold results

3. Output messages using h:outputFormat
– value gives base message
– nested f:param gives substitution values
– E.g.:

<h:outputFormat value="#{msgs.someName}">
<f:param value="value for 0th entry"/>
<f:param value="value for 1st entry"/>
</h:outputFormat>
1. Create multiple similarly named .properties
files
– blah.properties, blah_es.properties,
blah_es_mx.properties

2. Supply locale argument to f:view
<f:view
locale="#{facesContext.externalContext.request.loca
le}">

– Determines locale from browser language settings
– Can also set the Locale based on user input
locale="#{settings.selectedLocale}"
Jsf 2.0 in depth

Weitere ähnliche Inhalte

Was ist angesagt? (20)

JEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application DeploymentJEE Programming - 08 Enterprise Application Deployment
JEE Programming - 08 Enterprise Application Deployment
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
Introduction to CakePHP
Introduction to CakePHPIntroduction to CakePHP
Introduction to CakePHP
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
TomatoCMS in A Nutshell
TomatoCMS in A NutshellTomatoCMS in A Nutshell
TomatoCMS in A Nutshell
 
ICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax FrameworkICEfaces EE - Enterprise-ready JSF Ajax Framework
ICEfaces EE - Enterprise-ready JSF Ajax Framework
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java servlets
Java servletsJava servlets
Java servlets
 
JEE Programming - 04 Java Servlets
JEE Programming - 04 Java ServletsJEE Programming - 04 Java Servlets
JEE Programming - 04 Java Servlets
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Introduction to Cakephp
Introduction to CakephpIntroduction to Cakephp
Introduction to Cakephp
 
Jsp element
Jsp elementJsp element
Jsp element
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Introduction to servlet
Introduction to servletIntroduction to servlet
Introduction to servlet
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 

Andere mochten auch (6)

3 Jsf
3 Jsf3 Jsf
3 Jsf
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Java Server Faces 2
Java Server Faces 2Java Server Faces 2
Java Server Faces 2
 
Presentation jsf2
Presentation jsf2Presentation jsf2
Presentation jsf2
 
JSF2 par la pratique
JSF2 par la pratiqueJSF2 par la pratique
JSF2 par la pratique
 
Support de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec SpringSupport de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec Spring
 

Ähnlich wie Jsf 2.0 in depth

08052917365603
0805291736560308052917365603
08052917365603DSKUMAR G
 
AK 5 JSF 21 july 2008
AK 5 JSF   21 july 2008AK 5 JSF   21 july 2008
AK 5 JSF 21 july 2008gauravashq
 
Silicon Valley Code Camp - JSF Controller for Reusability
Silicon Valley Code Camp - JSF Controller for ReusabilitySilicon Valley Code Camp - JSF Controller for Reusability
Silicon Valley Code Camp - JSF Controller for Reusabilityjcruizjdev
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCBarry Gervin
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011Arun Gupta
 
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADF
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADFDont Reinvent the Wheel: Tips and Tricks for reuse in ADF
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADFLuc Bors
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_entechbed
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field WebSphere Portlet Factory: Davalen’s Practical Advice from the Field
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field Davalen LLC
 
Spring MVC
Spring MVCSpring MVC
Spring MVCyuvalb
 
Introduction to JSLink in 2013
Introduction to JSLink in 2013Introduction to JSLink in 2013
Introduction to JSLink in 2013Sparkhound Inc.
 

Ähnlich wie Jsf 2.0 in depth (20)

Jsf2.0 -4
Jsf2.0 -4Jsf2.0 -4
Jsf2.0 -4
 
Struts Intro
Struts IntroStruts Intro
Struts Intro
 
08052917365603
0805291736560308052917365603
08052917365603
 
AK 5 JSF 21 july 2008
AK 5 JSF   21 july 2008AK 5 JSF   21 july 2008
AK 5 JSF 21 july 2008
 
AK 4 JSF
AK 4 JSFAK 4 JSF
AK 4 JSF
 
Silicon Valley Code Camp - JSF Controller for Reusability
Silicon Valley Code Camp - JSF Controller for ReusabilitySilicon Valley Code Camp - JSF Controller for Reusability
Silicon Valley Code Camp - JSF Controller for Reusability
 
Jsf
JsfJsf
Jsf
 
Jsf
JsfJsf
Jsf
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADF
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADFDont Reinvent the Wheel: Tips and Tricks for reuse in ADF
Dont Reinvent the Wheel: Tips and Tricks for reuse in ADF
 
Don't Reinvent the Wheel - Tips and tricks for rease in Oracle ADF - Luc Bors
Don't Reinvent the Wheel - Tips and tricks for rease in Oracle ADF - Luc BorsDon't Reinvent the Wheel - Tips and tricks for rease in Oracle ADF - Luc Bors
Don't Reinvent the Wheel - Tips and tricks for rease in Oracle ADF - Luc Bors
 
Introduction to jsf 2
Introduction to jsf 2Introduction to jsf 2
Introduction to jsf 2
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_en
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field WebSphere Portlet Factory: Davalen’s Practical Advice from the Field
WebSphere Portlet Factory: Davalen’s Practical Advice from the Field
 
Migrando una app de angular.js a Blazor
Migrando una app de angular.js a BlazorMigrando una app de angular.js a Blazor
Migrando una app de angular.js a Blazor
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Introduction to JSLink in 2013
Introduction to JSLink in 2013Introduction to JSLink in 2013
Introduction to JSLink in 2013
 

Kürzlich hochgeladen

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Kürzlich hochgeladen (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Jsf 2.0 in depth

  • 2.  JSF Introduction  Page Navigation  Managed Beans  Expression Language  Properties File
  • 3.  Event Handling  HTML Library  Validation  JDBC in JSF  Data Tables
  • 4.  Ajax-4-JSF  Basic component tags  Advanced custom tags  Custom components
  • 5. Different views of JSF Comparing JSF to standard servlet/JSP technology Comparing JSF to Apache Struts
  • 6. A set of Web-based GUI controls and associated handlers? – JSF provides many prebuilt HTML-oriented GUI controls, along with code to handle their events. A device-independent GUI control framework? – JSF can be used to generate graphics in formats other than HTML, using protocols other than HTTP. A better Struts? – Like Apache Struts, JSF can be viewed as an MVC framework for building HTML forms, validating their values, invoking business logic, and displaying results.
  • 7. • Custom GUI controls – JSF provides a set of APIs and associated custom tags to create HTML forms that have complex interfaces • Event handling – JSF makes it easy to designate Java code that is invoked when forms are submitted. The code can respond to particular buttons, changes in particular values, certain user selections, and so on. • Managed beans – In JSP, you can use property="*" with jsp:setProperty to automatically populate a bean based on request parameters. JSF extends this capability and adds in several utilities, all of which serve to greatly simplify request param processing. • Expression Language – JSF provides a concise and powerful language for accessing bean properties and collection elements
  • 8. • Bigger learning curve – To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet APIs. To use MVC with JSF, you have to be comfortable with the standard JSP and servlet APIs and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller projects, near-term deadlines, and less experienced developers; you could spend as much time learning JSF as building your actual system. • Worse documentation – Compared to the standard servlet and JSP APIs, JSF has fewer online resources, and many first-time users find the online JSF documentation confusing and poorly organized. MyFaces is particularly bad.
  • 10. • When form submitted – A static page is displayed • Static result – No business logic, beans, or Java code of any sort – The return path is specified in the button itself. • Main points – Format of original form – Use of navigation-rule in faces-config.xml
  • 11. • Input form has following format: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> HTML markup <h:form> HTML markup and h:blah tags </h:form> HTML markup </f:view> • faces-config.xml specifies navigation rules: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE faces-config PUBLIC …> <faces-config> <navigation-rule> <from-view-id>/blah.jsp</from-view-id> <navigation-case> <from-outcome>some string</from-outcome> <to-view-id>/WEB-INF/results/something.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>
  • 12. The h:form element – ACTION is automatically self (current URL) – METHOD is automatically POST • Elements inside h:form – Use special tags to represent input elements • h:inputText corresponds to <INPUT TYPE="TEXT"> • h:inputSecret corresponds to <INPUT TYPE="PASSWORD"> • h:commandButton corresponds to <INPUT TYPE="SUBMIT"> – In later sections, we will see that input elements will be associated with bean properties – For static navigation, specify simple string as action of h:commandButton • String must match navigation rule from faces-config.xml
  • 13. register.jsp <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <!DOCTYPE …> <HTML> <HEAD>…</HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE">New Account Registration</TH></TR> </TABLE> <P> <h:form> Email address: <h:inputText/><BR> Password: <h:inputSecret/><BR> <h:commandButton value="Sign Me Up!" action="register"/> </h:form> </CENTER></BODY></HTML> </f:view>
  • 15. • General format <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE faces-config PUBLIC …> <faces-config> … </faces-config> • Specifying the navigation rules <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE faces-config PUBLIC …> <faces-config> <navigation-rule> <from-view-id>/register.jsp</from-view-id> <navigation-case> <from-outcome>register</from-outcome> <to-view-id>/WEB-INF/results/result.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>
  • 16. RequestDispatcher.forward used – So page can/should be in WEB-INF • Example code: – …/WEB-INF/results/result.jsp <!DOCTYPE …> <HTML> <HEAD>…</HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE">Success</TH></TR> </TABLE> <H2>You have registered successfully.</H2> </CENTER> </BODY></HTML>
  • 17. Note that the URL is unchanged
  • 18. Filename/URL correspondence – Actual files are of the form blah.jsp – URLs used are of the form blah.faces – You must prevent clients from directly accessing JSP pages • Since they would give erroneous results • Strategies – You cannot put input-form JSP pages in WEB-INF • Because URL must correspond directly to file location – So, use filter in web.xml. But: • You have to know the extension (.faces) • Assumes no non-JSF .jsp pages • This is a major drawback to JSF design
  • 19. FacesRedirectFilter public class FacesRedirectFilter implements Filter { private final static String EXTENSION = "faces"; public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; String uri = request.getRequestURI(); if (uri.endsWith(".jsp")) { int length = uri.length(); String newAddress = uri.substring(0, length-3) + EXTENSION; response.sendRedirect(newAddress); } else { // Address ended in "/" response.sendRedirect("index.faces"); } }
  • 22. • A form is displayed – Form uses f:view and h:form • The form is submitted to itself – Original URL and ACTION URL are http://…/blah.faces • A bean is instantiated – Listed in the managed-bean section of faces-config.xml • The action controller method is invoked – Listed in the action attribute of h:commandButton • The action method returns a condition – A string that matches from-outcome in the navigation rules in facesconfig.xml • A results page is displayed – The page is specified by to-view-id in the navigation rules in facesconfig.xml
  • 23. 1) Create a bean A) Properties for form data B) Action controller method C) Placeholders for results data 2) Create an input form A) Input fields refer to bean properties B) Button specifies action controller method that will return condition 3) Edit faces-config.xml A) Declare the bean B) Specify navigation rules 4) Create results pages – Output form data and results data with h:outputText 5) Prevent direct access to JSP pages – Use a filter that redirects blah.jsp to blah.faces
  • 24. • Collects info to see if user qualifies for health plan • When form submitted, one of two possible results will be displayed – User is accepted into health plan – User is rejected from health plan • Main points – Specifying an action controller in the form – Creating an action controller method in the bean – Using faces-config.xml to • Declare bean • Map return conditions to output pages
  • 25. • Specify the controller with #{beanName.methodName} <h:commandButton value="Sign Me Up!" action="#{healthPlanController.signup}"/> • Controller method returns strings corresponding to conditions – If null is returned, the form is redisplayed – Unlike with Struts, the controller need not extend a special class • Use faces-config.xml to declare the controller as follows <faces-config> <managed-bean> <managed-bean-name>controller name</managed-bean-name> <managed-bean-class>controller class</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config> • Add multiple navigation-rule entries to faces-config.xml – One for each possible string returned by the controller – If no string matches, the form is redisplayed
  • 26. (A) Properties for form data – Postponed until next session (B) Action controller method public class HealthPlanController { public String signup() { if (Math.random() < 0.2) { return("accepted"); } else { return("rejected"); } } } (C) Placeholders for results data – Postponed until next session
  • 27. • Same general syntax as in previous example – Except for action of commandButton <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> … <h:form> First name: <h:inputText/><BR> Last name: <h:inputText/><BR> ... <h:commandButton value="Sign Me Up!" action="#{healthPlanController.signup}"/> </h:form>… </f:view>
  • 28.
  • 29. (A) Declaring the bean … <faces-config> <managed-bean> <managed-bean-name> healthPlanController </managed-bean-name> <managed-bean-class> coreservlets.HealthPlanController </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> … </faces-config>
  • 30. (B) Specifying navigation rules – Outcomes should match return values of controller <faces-config> … (bean definitions from previous page) <navigation-rule> <from-view-id>/signup.jsp</from-view-id> <navigation-case> <from-outcome>accepted</from-outcome> <to-view-id>/WEB-INF/results/accepted.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>rejected</from-outcome> <to-view-id>/WEB-INF/results/rejected.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>
  • 31. • …/WEB-INF/results/accepted.jsp <!DOCTYPE …> <HTML> <HEAD>…</HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE">Accepted!</TH></TR> </TABLE> <H2>You are accepted into our health plan.</H2> Congratulations. </CENTER> </BODY></HTML>
  • 32. …/WEB-INF/results/accepted.jsp <!DOCTYPE …> <HTML> <HEAD>…</HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE">Accepted!</TH></TR> </TABLE> <H2>You are accepted into our health plan.</H2> Congratulations. </CENTER> </BODY></HTML>
  • 33. …/WEB-INF/results/rejected.jsp <!DOCTYPE …> <HTML> <HEAD>…</HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE">Rejected!</TH></TR> </TABLE> <H2>You are rejected from our health plan.</H2> Get lost. </CENTER> </BODY></HTML>
  • 34.
  • 35. • Use filter that captures url-pattern *.jsp – No changes from previous example
  • 36. • Wildcards in navigation rule – * for from-view-id matches any starting page <navigation-rule> <from-view-id>*</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/WEB-INF/results/success.jsp</to-view-id> </navigation-case> </navigation-rule> • Getting the request and response objects HttpServletRequest request = (HttpServletRequest)context.getRequest(); HttpServletResponse response = (HttpServletResponse)context.getResponse(); • In some environments, you cast results of getRequest and getResponse to values other than HttpServletRequest and HttpServletResponse E.g., in a portlet environment, you might cast result to PortletRequest and PortletResponse
  • 37. • If you have several different addresses in your app, it is OK to alternate <managed-bean> Stuff for bean1 </managed-bean> <navigation-rule> Rules for address that uses bean1 </navigation-rule> <managed-bean> Stuff for bean2 </managed-bean> <navigation-rule> Rules for address that uses bean2 </navigation-rule> – Of course, it is also OK to put all bean defs at the top, followed by all navigation rules.
  • 38. • Using beans to represent request parameters • Declaring beans in faces-config.xml • Referring to beans in input forms • Outputting bean properties
  • 39.
  • 40. 1) Create a bean A) Properties for form data B) Action controller method C) Placeholders for results data 2) Create an input form A) Input fields refer to bean properties B) Button specifies action controller method that will return condition 3) Edit faces-config.xml A) Declare the bean B) Specify navigation rules 4) Create results pages – Output form data and results data with h:outputText 5) Prevent direct access to JSP pages – Use a filter that redirects blah.jsp to blah.faces
  • 41. • When form submitted, three possible results – Error message re illegal email address – Error message re illegal password – Success • New features – Action controller obtains request data from within bean – Output pages access bean properties • Main points – Defining a bean with properties for the form data – Declaring beans in faces-config.xml – Outputting bean properties
  • 42. (1A) Form data public class RegistrationBean implements Serializable { private String email = "user@host"; private String password = ""; public String getEmail() { return(email); } public void setEmail(String email) { this.email = email; } public String getPassword() { return(password); } public void setPassword(String password) { this.password = password; }
  • 43. (1B) Action controller method public String register() { if ((email == null) || (email.trim().length() < 3) || (email.indexOf("@") == -1)) { suggestion = SuggestionUtils.getSuggestionBean(); return("bad-address"); } else if ((password == null) || (password.trim().length() < 6)) { suggestion = SuggestionUtils.getSuggestionBean(); return("bad-password"); } else { return("success"); } }
  • 44. (1C) Placeholder for storing results – Note that action controller method called business logic and placed the result in this placeholder private SuggestionBean suggestion; public SuggestionBean getSuggestion() { return(suggestion); }
  • 45. Result returned by business logic package coreservlets; import java.io.*; public class SuggestionBean implements Serializable { private String email; private String password; public SuggestionBean(String email, String password) { this.email = email; this.password = password; } public String getEmail() { return(email); } public String getPassword() { return(password); } }
  • 46. • Business logic public class SuggestionUtils { private static String[] suggestedAddresses = { "president@whitehouse.gov", "gates@microsoft.com", “tennyson@google.com", “s.jobes@apple.com" }; private static String chars = "abcdefghijklmnopqrstuvwxyz0123456789#@$%^&*?!"; public static SuggestionBean getSuggestionBean() { String address = randomString(suggestedAddresses); String password = randomString(chars, 8); return(new SuggestionBean(address, password)); } ... }
  • 47. • Similar to previous example, except – h:inputBlah tags given a value attribute identifying the corresponding bean property • Example code <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view>… <h:form> Email address: <h:inputText value="#{registrationBean.email}"/><BR> Password: <h:inputSecret value="#{registrationBean.password}"/><BR> <h:commandButton value="Sign Me Up!" action="#{registrationBean.register}"/> </h:form>… </f:view>
  • 48. The user@host value comes from the bean
  • 50. • (B) Define navigation rules … <faces-config> … <navigation-rule> <from-view-id>/register.jsp</from-view-id> <navigation-case> <from-outcome>bad-address</from-outcome> <to-view-id>/WEB-INF/results/bad-address.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>bad-password</from-outcome> <to-view-id>/WEB-INF/results/bad-password.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/WEB-INF/results/success.jsp</to-view-id> </navigation-case> </navigation-rule> </faces-config>
  • 51. • …/jsf-beans/WEB-INF/results/bad-address.jsp <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <!DOCTYPE …> <HTML> … <TABLE BORDER=5> <TR><TH CLASS="TITLE">Illegal Email Address</TH></TR> </TABLE> <P> The address "<h:outputText value="#{registrationBean.email}"/>" is not of the form username@hostname (e.g., <h:outputText value="#{registrationBean.suggestion.email}"/>). <P> Please <A HREF="register.faces">try again</A>. … </HTML> </f:view>
  • 54. • Use filter that captures url-pattern *.jsp – No changes from previous example
  • 55. Important • Shorthand notation for bean properties. – To reference the companyName property (i.e., result of the getCompanyName method) of a scoped variable (i.e. object stored in request, session, or application scope) or managed bean named company, you use #{company.companyName}. To reference the firstName property of the president property of a scoped variable or managed bean named company, you use #{company.president.firstName}. • Simple access to collection elements. – To reference an element of an array, List, or Map, you use #{variable[indexOrKey]}. Provided that the index or key is in a form that is legal for Java variable names, the dot notation for beans is interchangeable with the bracket notation for collections.
  • 56. Less Important • Succinct access to request parameters, cookies, and other request data. – To access the standard types of request data, you can use one of several predefined implicit objects. • A small but useful set of simple operators. – To manipulate objects within EL expressions, you can use any of several arithmetic, relational, logical, or empty-testing operators. • Conditional output. – To choose among output options, you do not have to resort to Java scripting elements. Instead, you can use #{test ? option1 : option2}. • Automatic type conversion. – The expression language removes the need for most typecasts and for much of the code that parses strings as numbers. • Empty values instead of error messages. – In most cases, missing values or
  • 57. To enforce EL-only with no scripting, use scriptinginvalid in web.xml – Still permits both the JSF EL and the JSP 2.0 EL <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd" version="2.4"> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </web-app>
  • 58. import java.util.*; public class TestBean { private Date creationTime = new Date(); private String greeting = "Hello"; public Date getCreationTime() { return(creationTime); } public String getGreeting() { return(greeting); } public double getRandomNumber() { return(Math.random()); } }
  • 59. <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE ...> <faces-config> <managed-bean> <managed-bean-name>testBean</managed-bean-name> <managed-bean-class> coreservlets.TestBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> ... </faces-config>
  • 60. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> ... <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE">Accessing Bean Properties</TH></TR> </TABLE> <UL> <LI>Creation time: <h:outputText value="#{testBean.creationTime}"/> <LI>Greeting: <h:outputText value="#{testBean.greeting}"/> <LI>Random number: <h:outputText value="#{testBean.randomNumber}"/> </UL> </BODY></HTML> </f:view>
  • 61.
  • 62. public class NameBean { private String firstName = "Missing first name"; private String lastName = "Missing last name"; public NameBean() {} public NameBean(String firstName, String lastName) { setFirstName(firstName); setLastName(lastName); } public String getFirstName() { return(firstName); } public void setFirstName(String newFirstName) { firstName = newFirstName; } ... }
  • 63. public class CompanyBean { private String companyName; private String business; public CompanyBean(String companyName, String business) { setCompanyName(companyName); setBusiness(business); } public String getCompanyName() { return(companyName); } public void setCompanyName(String newCompanyName) { companyName = newCompanyName; } ... }
  • 64. public class EmployeeBean { private NameBean name; private CompanyBean company; public EmployeeBean(NameBean name, CompanyBean company) { setName(name); setCompany(company); } public EmployeeBean() { this(new NameBean("Marty", "Hall"), new CompanyBean("coreservlets.com", "J2EE Training and Consulting")); } public NameBean getName() { return(name); } public void setName(NameBean newName) { name = newName; } ... }
  • 66. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> ... <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE">Using Nested Bean Properties</TH></TR> </TABLE> <UL> <LI>Employee's first name: <h:outputText value="#{employee.name.firstName}"/> <LI>Employee's last name: <h:outputText value="#{employee.name.lastName}"/> <LI>Name of employee's company: <h:outputText value="#{employee.company.companyName}"/> <LI>Business area of employee's company: <h:outputText value="#{employee.company.business}"/> </UL> </BODY></HTML> </f:view>
  • 67.
  • 68. • Loading properties files • Simple messages • Parameterized messages • Internationalized messages
  • 69. 1. Create a .properties file • Contains simple keyName=value pairs • Must be deployed to WEB-INF/classes • In Eclipse, this means you put it in "src" folder 2. Load file with f:loadBundle – basename gives base file name – var gives scoped variable (Map) that will hold results • Relative to WEB-INF/classes, .properties assumed • E.g., for WEB-INF/classes/messages.properties <f:loadBundle basename="messages" var="msgs"/> • E.g., for WEB-INF/classes/package1/test.properties <f:loadBundle basename="package1.test" var="msgs"/> 3. Output messages using normal EL – #{msgs.keyName}
  • 70. 1. Create a .properties file in/under WEB-INF/classes – Values contain {0}, {1}, {2}, etc. – E.g., someName=blah {0} blah {1} – Warning: MyFaces bug prevents single quotes in values 2. Load file with f:loadBundle as before – basename gives base file name – var gives scoped variable (Map) that will hold results 3. Output messages using h:outputFormat – value gives base message – nested f:param gives substitution values – E.g.: <h:outputFormat value="#{msgs.someName}"> <f:param value="value for 0th entry"/> <f:param value="value for 1st entry"/> </h:outputFormat>
  • 71. 1. Create multiple similarly named .properties files – blah.properties, blah_es.properties, blah_es_mx.properties 2. Supply locale argument to f:view <f:view locale="#{facesContext.externalContext.request.loca le}"> – Determines locale from browser language settings – Can also set the Locale based on user input locale="#{settings.selectedLocale}"