Free Essay

Sample

In:

Submitted By rabh21santa
Words 11815
Pages 48
Java Server Faces (JSF) Tutorial

JAVA SERVER FACES TUTORIAL

Simply Easy Learning by tutorialspoint.com

tutorialspoint.com i ABOUT THE TUTORIAL

Java Server Faces Tutorial
JavaServer Faces (JSF) is a Java-based web application framework intended to simplify development integration of webbased user interfaces. JavaServer Faces is a standardized display technology which was formalized in a specification through the Java Community Process. This tutorial will teach you basic JSF concepts and will also take you through various advance concepts related to JSF framework.

Audience
This tutorial has been prepared for the beginners to help them understand basic JSF programming. After completing this tutorial you will find yourself at a moderate level of expertise in JSF programming from where you can take yourself to next levels.

Prerequisites
Before proceeding with this tutorial you should have a basic understanding of Java programming language, text editor and execution of programs etc. Because we are going to develop web based applications using JSF, so it will be good if you have understanding on other web technologies like, HTML, CSS, AJAX etc.

Copyright & Disclaimer Notice
 All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com

ii

T able of Contents
Java Server Faces Tutorial ....................................................... i Audience ................................................................................... i Prerequisites ............................................................................. i Copyright & Disclaimer Notice ................................................... i JSF-Overview ........................................................................... 1 JSF - Environment Setup .......................................................... 3 JSF - Architecture..................................................................... 9 JSF – Life Cycle ...................................................................... 11 JSF – First Application ........................................................... 13 JSF – Page Navigation ............................................................ 25 JSF – Basic Tags ..................................................................... 38 JSF – Convertor Tags .............................................................. 41 JSF – Validator Tags ............................................................... 42 JSF – Data Table .................................................................... 43 JSF – Composite Components ................................................. 44 JSF – Ajax .............................................................................. 49 JSF – Event Handling ............................................................. 53 JSF – JDBC Integration ......................................................... 69 JSF – Spring Integration ......................................................... 75 JSF – Expression Language ..................................................... 82 JSF - Internationalization ....................................................... 85

iii

CHAPTER

1

JSF-Overview
This chapter describes the basic definition and concepts of Java Server Faces (JSF).

What is JSF?

J
    

ava Server Faces (JSF) is a MVC web framework that simplifies the construction of user interfaces (UI) for

server-based applications by using reusable UI components in a page. JSF provides facility to connect UI widgets with data sources and to server-side event handlers. The JSF specification defines a set of standard UI components and provides an Application Programming Interface (API) for developing components. JSF enables the reuse and extension of the existing standard UI components.

Benefits
JSF reduces the effort in creating and maintaining applications which will run on a Java application server and will render application UI on to a target client. JSF facilitates Web application development by proving reusable UI components making easy data transfer between UI components managing UI state across multiple server requests enabling implementation of custom components wiring client side event to server side application code

JSF UI component model
JSF provides developers capability to create Web application from collections of UI components that can render themselves in different ways for multiple client types (for example HTML browser, wireless or WAP devise). JSF provides



Core library

TUTORIALSPOINT Simply Easy Learning

Page 1

  

A set of base UI components - standard HTML input elements Extension of the base UI components to create additional UI component libraries or to extend existing components. Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client types.

TUTORIALS POINT Simply Easy Learning

Page 2

CHAPTER

2

JSF - Environment Setup
This chapter describes the environment setup of Java Server Faces (JSF)

T
JDK

his tutorial will guide you on how to prepare a development environment to start your work with JSF

Framework. This tutorial will also teach you how to setup JDK, Eclipse, Maven, and Tomcat on your machine before you setup JSF Framework:

System Requirement
JSF requires JDK 1.5 or higher so the very first requirement is to have JDK installed in your machine. 1.5 or above. no minimum requirement. no minimum requirement. no minimum requirement.

Memory Disk Space Operating System

Follow the given steps to setup your environment to start with JSF application development.

Step 1 - Verify Java installation on your machine
Now open console and execute the following java command. OS Windows Linux Mac Task Open Command Console Open Command Terminal Open Terminal Command c:\> java -version $ java -version machine:~ joseph$ java -version

Let's verify the output for all the operating systems: OS Windows Generated Output java version "1.6.0_21"

TUTORIALS POINT Simply Easy Learning

Page 3

Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) Linux java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)

Mac

Step 2 - Setup Java Development Kit (JDK):
If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example

OS Windows Linux Mac

Output Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21 export JAVA_HOME=/usr/local/java-current export JAVA_HOME=/Library/Java/Home

Append Java compiler location to System Path. OS Windows Linux Mac Output Append the string ;%JAVA_HOME%\bin to the end of the system variable, Path. export PATH=$PATH:$JAVA_HOME/bin/ not required

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.

Step 3 - Setup Eclipse IDE
All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine based on your operating system. To install Eclipse IDE, download the latest Eclipse binaries with WTP support fromhttp://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe

TUTORIALS POINT Simply Easy Learning

Page 4

%C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine: $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display following result:

Step 4: Download Maven archive
Download Maven 2.2.1 from http://maven.apache.org/download.html OS Windows Linux Mac Archive name apache-maven-2.0.11-bin.zip apache-maven-2.0.11-bin.tar.gz apache-maven-2.0.11-bin.tar.gz

TUTORIALS POINT Simply Easy Learning

Page 5

Step 5: Extract the Maven archive
Extract the archive, to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive. OS Windows Linux Mac Location (can be different based on your installation) C:\Program Files\Apache Software Foundation\apache-maven-2.2.1 /usr/local/apache-maven /usr/local/apache-maven

Step 6: Set Maven environment variables
Add M2_HOME, M2, MAVEN_OPTS to environment variables. OS Output Set the environment variables using system properties. M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-2.2.1 M2=%M2_HOME%\bin MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1 export M2=%M2_HOME%\bin export MAVEN_OPTS=-Xms256m -Xmx512m Open command terminal and set environment variables. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1 export M2=%M2_HOME%\bin export MAVEN_OPTS=-Xms256m -Xmx512m

Windows

Linux

Mac

Step 7: Add Maven bin directory location to system path
Now append M2 variable to System Path OS Windows Linux Mac Output Append the string ;%M2% to the end of the system variable, Path. export PATH=$M2:$PATH export PATH=$M2:$PATH

Step 8: Verify Maven installation
Now open console, execute the following mvn command.

TUTORIALS POINT Simply Easy Learning

Page 6

OS Windows Linux Mac

Task Open Command Console Open Command Terminal Open Terminal

Command c:\> mvn --version $ mvn --version machine:~ joseph$ mvn --version

Finally, verify the output of the above commands, which should be something as follows: OS Windows Output Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Java version: 1.6.0_21 Java home: C:\Program Files\Java\jdk1.6.0_21\jre

Linux

Mac

Step 9: Setup Apache Tomcat:
You can download the latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-6.0.33 on windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations. Tomcat can be started by executing the following commands on windows machine, or you can simply double click on startup.bat %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-6.0.33\bin\startup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine: $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-6.0.33/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:

TUTORIALS POINT Simply Easy Learning

Page 7

Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org Tomcat can be stopped by executing the following commands on windows machine: %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine: $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

TUTORIALS POINT Simply Easy Learning

Page 8

CHAPTER

3

JSF - Architecture

J

SF technology is a framework for developing, building server side User Interface Components and using them

in a web application. JSF technology is based on the Model View Controller (MVC) architecture for separating logic from presentation.

What is MVC Design Pattern?
MVC design pattern designs an application using three separate modules: Module Model View Controller Description Carries Data and login Shows User Interface Handles processing of an application.

Purpose of MVC design pattern is to separate model and presentation to enable developers to set focus on their core skills and collaborate more clearly. Web Designers have to concentrate only on view layer rather than model and controller layer. Developers can change the code for model and typically need not to change view layer. Controllers are used to process user actions. In this process layer model and views may be changed.

JSF Architecture
A JSF application is similar to any other Java technology-based web application; it runs in a Java servlet container, and contains

 JavaBeans components as models containing application-specific functionality and data  A custom tag library for representing event handlers and validators  A custom tag library for rendering UI components  UI components represented as stateful objects on the server  Server-side helper classes

TUTORIALS POINT Simply Easy Learning

Page 9

 Validators, event handlers, and navigation handlers  Application configuration resource file for configuring application resources

There are controllers which can be used to perform user actions. UI can be created by web page authors and the business logic can be utilized by managed beans. JSF provides several mechanisms for rendering an individual component. It is up to the web page designer to pick the desired representation, and the application developer doesn't need to know which mechanism was used to render a JSF UI component.

TUTORIALS POINT Simply Easy Learning

Page 10

CHAPTER

4

JSF – Life Cycle

J
     

SF application lifecycle consist of six phases which are as follows

Restore view phase Apply request values phase; process events Process validations phase; process events Update model values phase; process events Invoke application phase; process events Render response phase

The six phases show the order in which JSF processes a form. The list shows the phases in their likely order of execution with event processing at each phase.

Phase 1: Restore view
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.

TUTORIALS POINT Simply Easy Learning

Page 11

During this phase, the JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance will now contains all the information required to process a request.

Phase 2: Apply request values
After the component tree is created/restored, each component in component tree uses decode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors. If any decode methods / event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.

Phase 3: Process validation
During this phase, the JSF processes all validators registered on component tree. It examines the component attribute rules for the validation and compares these rules to the local value stored for the component. If the local value is invalid, the JSF adds an error message to the FacesContext instance, and the life cycle advances to the render response phase and display the same page again with the error message.

Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree and set the corresponding server-side object properties to the components' local values. The JSF will update the bean properties corresponding to input component's value attribute. If any updateModels methods called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.

Phase 5: Invoke application
During this phase, the JSF handles any application-level events, such as submitting a form / linking to another page.

Phase 6: Render response
During this phase, the JSF asks container/application server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the component tree is already built so components need not to be added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page. After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase.

TUTORIALS POINT Simply Easy Learning

Page 12

CHAPTER

5

JSF – First Application

T

o create a simple JSF application, we'll use maven-archetype-webapp plugin. In example below, We'll

create a maven based web application project in C:\JSF folder.

Create Project
Let's open command console, go the C:\ > JSF directory and execute the following mvn command. C:\JSF>mvn archetype:create -DgroupId=com.tutorialspoint.test -DartifactId=helloworld -DarchetypeArtifactId=maven-archetype-webapp Maven will start processing and will create the complete java web application project structure. [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'archetype'. [INFO] ------------------------------------------------------------[INFO] Building Maven Default Project [INFO] task-segment: [archetype:create] (aggregator-style)

[INFO] ------------------------------------------------------------[INFO] [archetype:create {execution: default-cli}] [INFO] Defaulting package to group ID: com.tutorialspoint.test [INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp: checking for updates from central [INFO] ------------------------------------------------------------[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:RELEASE [INFO] -------------------------------------------------------------

TUTORIALS POINT Simply Easy Learning

Page 13

[INFO] Parameter: groupId, Value: com.tutorialspoint.test [INFO] Parameter: packageName, Value: com.tutorialspoint.test [INFO] Parameter: package, Value: com.tutorialspoint.test [INFO] Parameter: artifactId, Value: helloworld [INFO] Parameter: basedir, Value: C:\JSF [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\JSF\helloworld [INFO] ------------------------------------------------------------[INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------[INFO] Total time: 7 seconds [INFO] Finished at: Mon Nov 05 16:05:04 IST 2012 [INFO] Final Memory: 12M/84M [INFO] ------------------------------------------------------------Now go to C:/JSF directory. You'll see a java web application project created named helloworld (as specified in artifactId). Maven uses a standard directory layout as shown below:

Using above example, we can understand following key concepts Folder Structure helloworld src/main/wepapp src/main/resources Description contains src folder and pom.xml contains WEB-INF folder and index.jsp page it contains images/properties files (In above example, we need to create this structure manually).

Add JSF capability to Project

TUTORIALS POINT Simply Easy Learning

Page 14

Add the JSF dependencies as shown below. com.sun.faces jsf-api 2.1.7 com.sun.faces jsf-impl 2.1.7

Complete POM.xml 4.0.0 com.tutorialspoint.test helloworld war 1.0-SNAPSHOT helloworld Maven Webapp http://maven.apache.org junit junit 3.8.1 test com.sun.faces jsf-api 2.1.7 com.sun.faces jsf-impl 2.1.7 helloworld org.apache.maven.plugins maven-compiler-plugin 2.3.1 1.6 1.6

TUTORIALS POINT Simply Easy Learning

Page 15

Prepare Eclipse project
Let's open command console, go the C:\ > JSF > helloworld directory and execute the following mvncommand. C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion=2.0 Maven will start processing and will create the eclipse ready project and will add wtp capability. Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/ maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom 5K downloaded (maven-compiler-plugin-2.3.1.pom)

Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/ maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar 29K downloaded (maven-compiler-plugin-2.3.1.jar)

[INFO] Searching repository for plugin with prefix: 'eclipse'. [INFO] -----------------------------------------------------------[INFO] Building helloworld Maven Webapp [INFO] task-segment: [eclipse:eclipse]

[INFO] -----------------------------------------------------------[INFO] Preparing eclipse:eclipse [INFO] No goals needed for project - skipping [INFO] [eclipse:eclipse {execution: default-cli}] [INFO] Adding support for WTP version 2.0. [INFO] Using Eclipse Workspace: null [INFO] Adding default classpath container: org.eclipse.jdt. launching.JRE_CONTAINER Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom 12K downloaded (jsf-api-2.1.7.pom)

Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom 10K downloaded (jsf-impl-2.1.7.pom)

Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar

TUTORIALS POINT Simply Easy Learning

Page 16

619K downloaded

(jsf-api-2.1.7.jar)

Downloading: http://repo.maven.apache.org/ com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar 1916K downloaded (jsf-impl-2.1.7.jar)

[INFO] Wrote settings to C:\JSF\helloworld\.settings\ org.eclipse.jdt.core.prefs [INFO] Wrote Eclipse project for "helloworld" to C:\JSF\helloworld. [INFO] [INFO] ----------------------------------------------------------[INFO] BUILD SUCCESSFUL [INFO] ----------------------------------------------------------[INFO] Total time: 6 minutes 7 seconds [INFO] Finished at: Mon Nov 05 16:16:25 IST 2012 [INFO] Final Memory: 10M/89M [INFO] -----------------------------------------------------------

Import project in Eclipse
     
Now import project in eclipse using Import wizard Go to File > Import... > Existing project into workspace Select root directory to helloworld Keep Copy projects into workspace to be checked. Click Finish button. Eclipse will import and copy the project in its workspace C:\ > Projects > Data > WorkSpace

TUTORIALS POINT Simply Easy Learning

Page 17

Create a Managed Bean
Create a package structure under src > main > java as com > tutorialspoint > test . Create HelloWorld.java class in this package. Update the code of HelloWorld.java as shown below.

package com.tutorialspoint.test; import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloWorld", eager = true) public class HelloWorld { public HelloWorld() { System.out.println("HelloWorld started!"); } public String getMessage() { return "Hello World!"; } }

Create a JSF page
Create a page home.xhtml under webapp folder. Update the code of home.xhtml as shown below.

JSF Tutorial! #{helloWorld.message}

Build the project
   
Select helloworld project in eclipse Use Run As wizard Select Run As > Maven package Maven will start building the project and will create helloworld.war under C:\ > Projects > Data > WorkSpace > helloworld > target folder [INFO] Scanning for projects... [INFO] ----------------------------------------------------[INFO] Building helloworld Maven Webapp [INFO]

TUTORIALS POINT Simply Easy Learning

Page 18

[INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT [INFO] task-segment: [package] [INFO] ----------------------------------------------------[INFO] [resources:resources] [INFO] Using default encoding to copy filtered resources. [INFO] [compiler:compile] [INFO] Nothing to compile - all classes are up to date [INFO] [resources:testResources] [INFO] Using default encoding to copy filtered resources. [INFO] [compiler:testCompile] [INFO] No sources to compile [INFO] [surefire:test] [INFO] Surefire report directory: C:\Projects\Data\WorkSpace\helloworld\target\surefire-reports

------------------------------------------------------T E S T S ------------------------------------------------------There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] [war:war] [INFO] Packaging webapp [INFO] Assembling webapp[helloworld] in [C:\Projects\Data\WorkSpace\helloworld\target\helloworld] [INFO] Processing war project [INFO] Webapp assembled in[150 msecs] [INFO] Building war: C:\Projects\Data\WorkSpace\helloworld\target\helloworld.war [INFO] -----------------------------------------------[INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------

TUTORIALS POINT Simply Easy Learning

Page 19

[INFO] Total time: 3 seconds [INFO] Finished at: Mon Nov 05 16:34:46 IST 2012 [INFO] Final Memory: 2M/15M [INFO] ------------------------------------------------

Deploy WAR file
    
Stop the tomcat server. Copy the helloworld.war file to tomcat installation directory > webapps folder. Start the tomcat server. Look inside webapps directory, there should be a folder helloworld got created. Now helloworld.war is successfully deployed in Tomcat Webserver root.

Run Application
Enter a url in web browser: http://localhost:8080/helloworld/home.jsf to launch the application Server name (localhost) and port (8080) may vary as per your tomcat configuration.

TUTORIALS POINT Simply Easy Learning

Page 20

CHAPTER

6

JSF – Managed Beans

M
    

anaged Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a

java bean managed by JSF framework. The managed bean contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value). Managed beans works as Model for UI component. Managed Bean can be accessed from JSF page. In JSF 1.2,a managed bean had to register it in JSF configuration file such as faces-config.xml. From JSF 2.0 onwards, Managed beans can be easily registered using annotations. This approach keeps beans and there registration at one place and it becomes easier to manage.

Using XML Configuration helloWorld com.tutorialspoint.test.HelloWorld request message com.tutorialspoint.test.Message request

Using Annotation
@ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value="#{message}") private Message message; ...

TUTORIALS POINT Simply Easy Learning

Page 21

}

@ManagedBean Annotation
@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case it would be helloWorld. Another important attribute is eager. If eager="true" then managed bean is created before it is requested for the first time otherwise "lazy" initialization is used in which bean will be created only when it is requested.

Scope Annotations
Scope annotations set the scope into which the managed bean will be placed. If scope is not specified then bean will default to request scope. Each scope is briefly discussed below Scope @RequestScoped Description Bean lives as long as the HTTP request-response lives. It get created upon a HTTP request and get destroyed when the HTTP response associated with the HTTP request is finished. Bean lives as long as a single EL evaluation. It get created upon an EL evaluation and get destroyed immediately after the EL evaluation. Bean lives as long as user is interacting with the same JSF view in the browser window/tab. It get created upon a HTTP request and get destroyed once user postback to a different view. Bean lives as long as the HTTP session lives. It get created upon the first HTTP request involving this bean in the session and get destroyed when the HTTP session is invalidated. Bean lives as long as the web application lives. It get created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and get destroyed when the web application shuts down. Bean lives as long as the bean's entry in the custom Map which is created for this scope lives.

@NoneScoped

@ViewScoped

@SessionScoped

@ApplicationScoped

@CustomScoped

@ManagedProperty Annotation
JSF is a simple static Dependency Injection(DI) framework.Using @ManagedProperty annotation a managed bean's property can be injected in another managed bean.

Example Application
Let us create a test JSF application to test the above annotations for managed beans. Step Description

TUTORIALS POINT Simply Easy Learning

Page 22

1 2 3 4 5 6

Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF Create Application chapter. Modify HelloWorld.java as explained below. Keep rest of the files unchanged. Create Message.java under a package com.tutorialspoint.test as explained below. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

HelloWorld.java package com.tutorialspoint.test; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; @ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value="#{message}") private Message messageBean; private String message; public HelloWorld() { System.out.println("HelloWorld started!"); } public String getMessage() { if(messageBean != null){ message = messageBean.getMessage(); } return message; } public void setMessageBean(Message message) { this.messageBean = message; } }

Message.java package com.tutorialspoint.test; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name = "message", eager = true) @RequestScoped public class Message {

TUTORIALS POINT Simply Easy Learning

Page 23

private String message = "Hello World!"; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

home.xhtml JSF Tutorial! #{helloWorld.message} Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 24

CHAPTER

7

JSF – Page Navigation

N
   

avigation rules are those rules provided by JSF Framework which describe which view is to be shown

when a button or link is clicked. Navigation rules can be defined in JSF configuration file named faces-config.xml. Navigation rules can be defined in managed beans. Navigation rules can contain conditions based on which resulted view can be shown. JSF 2.0 provides implicit navigation as well in which there is no need to define navigation rules as such.

Implicit Navigation
JSF 2.0 provides auto view page resolver mechanism named implicit navigation. In this case you only need to put view name in action attribute and JSF will search the correct view page automatically in the deployed application.

TUTORIALS POINT Simply Easy Learning

Page 25

Auto navigation in JSF page
Set view name in action attribute of any JSF UI Component. Using JSF outcome

Here when Page2 button is clicked, JSF will resolve the view name, page2 as page2.xhtml extension, and find the corresponding view file page2.xhtml in the current directory.

Auto navigation in Managed Bean
Define a method in managed bean to return a view name.

ManagedBean(name = "navigationController", eager = true)
@RequestScoped public class NavigationController implements Serializable { public String moveToPage1(){ return "page1"; } } Get view name in action attribute of any JSF UI Component using managed bean. Using Managed Bean

TUTORIALS POINT Simply Easy Learning

Page 26

Here when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml extension, and find the corresponding view file page1.xhtml in the current directory.

Conditional Navigation
Using managed bean we can very easily control the navigation. Look at following code in a managed bean.

ManagedBean(name = "navigationController", eager = true)
@RequestScoped public class NavigationController implements Serializable {

//this managed property will read value from request parameter pageId @ManagedProperty(value="#{param.pageId}") private String pageId; //condional navigation based on pageId //if pageId is 1 show page1.xhtml,

TUTORIALS POINT Simply Easy Learning

Page 27

//if pageId is 2 show page2.xhtml //else show home.xhtml public String showPage(){ if(pageId == null){ return "home"; } if(pageId.equals("1")){ return "page1"; }else if(pageId.equals("2")){ return "page2"; }else{ return "home"; } } } Pass pageId as a request parameter in JSF UI Component. Here when "Page1" button is clicked

    

JSF will create a request with parameter pageId=1 Then JSF will pass this parameter to managed property pageId of navigationController Now navigationController.showPage() is called which will return view as page1 after checking the pageId JSF will resolve the view name, page1 as page1.xhtml extension and find the corresponding view file page1.xhtml in the current directory

TUTORIALS POINT Simply Easy Learning

Page 28

Resolving Navigation based on from-action
JSF provides navigation resolution option even if managed bean different methods returns same view name.

Look at following code in a managed bean. public String processPage1(){ return "page"; } public String processPage2(){ return "page"; } To resolve views, define following navigation rule in faces-config.xml home.xhtml

TUTORIALS POINT Simply Easy Learning

Page 29

#{navigationController.processPage1} page page1.jsf #{navigationController.processPage2} page page2.jsf Here when Page1 button is clicked

 

navigationController.processPage1() is called which will return view as page JSF will resolve the view name, page1 as view name is page and from-action in faces-

config isnavigationController.processPage1



and find the corresponding view file page1.xhtml in the current directory

Forward vs Redirect
JSF by default performs a server page forward while navigating to another page and the URL of the application do not changes. To enable the page redirection, append faces-redirect=true at the end of the view name.

TUTORIALS POINT Simply Easy Learning

Page 30

Forward Redirect Here when Page1 button under Forward is clicked

Here when Page1 button under Redirect is clicked

TUTORIALS POINT Simply Easy Learning

Page 31

Example Application
Let us create a test JSF application to test all of the above navigation examples. Step 1 2 3 4 5 6 7 8 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF Create Application chapter. Create NavigationController.java under a package com.tutorialspoint.test as explained below. Create faces-config.xml under a WEB-INF folder and updated its contents as explained below. Update web.xml under a WEB-INF folder as explained below. Create page1.xhtml and page2.xhtml and modify home.xhtml under a webapp folder as explained below. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

NavigationController.java package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; @ManagedBean(name = "navigationController", eager = true) @RequestScoped public class NavigationController implements Serializable { private static final long serialVersionUID = 1L;

TUTORIALS POINT Simply Easy Learning

Page 32

@ManagedProperty(value="#{param.pageId}") private String pageId; public String moveToPage1(){ return "page1"; } public String moveToPage2(){ return "page2"; } public String moveToHomePage(){ return "home"; } public String processPage1(){ return "page"; } public String processPage2(){ return "page"; } public String showPage(){ if(pageId == null){ return "home"; } if(pageId.equals("1")){ return "page1"; }else if(pageId.equals("2")){ return "page2"; }else{ return "home"; } } public String getPageId() { return pageId; } public void setPageId(String pageId) { this.pageId = pageId; } }

faces-config.xml

TUTORIALS POINT Simply Easy Learning

Page 33

home.xhtml #{navigationController.processPage1} page page1.jsf #{navigationController.processPage2} page page2.jsf

web.xml Archetype Created Web Application javax.faces.PROJECT_STAGE Development javax.faces.CONFIG_FILES /WEB-INF/faces-config.xml Faces Servlet javax.faces.webapp.FacesServlet Faces Servlet *.jsf

page1.xhtml This is Page1

TUTORIALS POINT Simply Easy Learning

Page 34

page2.xhtml This is Page2

home.xhtml Implicit Navigation Using Managed Bean Using JSF outcome Conditional Navigation

TUTORIALS POINT Simply Easy Learning

Page 35

"From Action" Navigation Forward vs Redirection Navigation Forward Redirect Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 36

TUTORIALS POINT Simply Easy Learning

Page 37

CHAPTER

8

JSF – Basic Tags

J
S.N. 1 2 3 4 5 6 7 8 9 10

SF provides a standard HTML tag library. These tags get rendered into corresponding html output.

For these tags you need to use the following namespaces of URI in html node. Following are important Basic Tags in JSF 2.0: Tag & Description h:inputText Renders a HTML input of type="text", text box. h:inputSecret Renders a HTML input of type="password", text box. h:inputTextarea Renders a HTML textarea field. h:inputHidden Renders a HTML input of type="hidden". h:selectBooleanCheckbox Renders a single HTML check box. h:selectManyCheckbox Renders a group of HTML check boxes. h:selectOneRadio Renders a single HTML radio button. h:selectOneListbox Renders a HTML single list box. h:selectManyListbox Renders a HTML multiple list box. h:selectOneMenu Renders a HTML combo box.

TUTORIALS POINT Simply Easy Learning

Page 38

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

h:outputText Renders a HTML text. h:outputFormat Renders a HTML text. It accepts parameters. h:graphicImage Renders an image. h:outputStylesheet Includes a CSS style sheet in HTML output. h:outputScript Includes a script in HTML output. h:commandButton Renders a HTML input of type="submit" button. h:Link Renders a HTML anchor. h:commandLink Renders a HTML anchor. h:outputLink Renders a HTML anchor. h:panelGrid Renders an HTML Table in form of grid. h:message Renders message for a JSF UI Component. h:messages Renders all message for JSF UI Components. f:param Pass parameters to JSF UI Component. f:attribute Pass attribute to a JSF UI Component. f:setPropertyActionListener Sets value of a managed bean's property

TUTORIALS POINT Simply Easy Learning

Page 39

CHAPTER

9

JSF – Facelets Tags

J

SF provides special tags to create common layout for a web application called facelets tags. These tags gives

flexibility to manage common parts of a multiple pages at one place. For these tags you need to use the following namespaces of URI in html node.

Following are important Facelets Tags in JSF 2.0:

S.N.

Tag & Description Templates We'll demonstrate how to use templates using following tags


1

Parameters We'll demonstrate how to pass parameters to a template file using following tag

  

2



Custom We'll demonstrate how to create custom tags. Remove We'll demonstrate capability to remove JSF code from generated HTML page.

3 4

TUTORIALS POINT Simply Easy Learning

Page 40

11
JSF – Convertor Tags

CHAPTER

J

SF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice

versa. For example, these tags can convert a text into date object and can validate the format of input as well. For these tags you need to use the following namespaces of URI in html node.

Following are important Convertor Tags in JSF 2.0:

S.N. 1 2 3

Tag & Description f:convertNumber Converts a String into a Number of desired format f:convertDateTime Converts a String into a Date of desired format Custom Convertor Creating a custom convertor

TUTORIALS POINT Simply Easy Learning

Page 41

11
JSF – Validator Tags

CHAPTER

J
S.N. 1 2 3 4 5

SF provides inbuilt validators to validate its UI components. These tags can validates length of field, type of

input which can be a custom object. For these tags you need to use the following namespaces of URI in html node. Following are important Validator Tags in JSF 2.0: Tag & Description f:validateLength Validates length of a string f:validateLongRange Validates range of numeric value f:validateDoubleRange Validates range of float value f:validateRegex Validate JSF component with a given regular expression. Custom Validator Creating a custom validator

TUTORIALS POINT Simply Easy Learning

Page 42

12
JSF – Data Table

CHAPTER

J
 

SF provides a rich control named DataTable to render and format html tables.

DataTable can iterate over collection or array of values to display data. DataTable provides attributes to modify its data in easy way.

HTML Header Following are important DataTable operations in JSF 2.0: S.N. 1 2 3 4 5 Tag & Description
Display DataTable

How to display a datatable
Add data

How to add a new row in a datatable
Edit data

How to edit a row in a datatable
Delete data

How to delete a row in datatable
Using DataModel

Use DataModel to display row numbers in a datatable

TUTORIALS POINT Simply Easy Learning

Page 43

13
JSF – Composite Components

CHAPTER

J
1a

SF provides developer a powerful capability to define own custom components which can be used to render

custom contents.

Define Custom Component
Defining a custom component in JSF is a two step process Step No. Description Create a resources folder. Create a xhtml file in resources folder with a composite namespace. Use composite tags composite:interface, composite:attribute andcomposite:implementation, to define content of the composite component. Use cc.attrs in composite:implementation to get variable defined using composite:attributein composite:interface.

1b

Step 1a: Create loginComponent.xhtml
Use composite namespace in html header.

custom

component

:

Create a folder tutorialspoint in resources folder and create a file loginComponent.xhtml in it

...

Step 1b: Use composite tags : loginComponent.xhtml
Following table describes use of composite tags.

TUTORIALS POINT Simply Easy Learning

Page 44

S.N. 1 2

tag & Description composite:interface Declare configurable values to be used in composite:implementation composite:attribute Configuration values are declared using this tag composite:implementation Declares JSF component. Can access the configurable values defined in composite:interface using #{cc.attrs.attribute-name} expression.

3

#{cc.attrs.usernameLabel} :

Use Custom Component
Using a custom component in JSF is a simple process Step No. 2a 2b Description Create a xhtml file and use custom component's namespace. Namespace will the http://java.sun.com/jsf/ where folder-name is folder in resources directory containing the custom compoent Use the custom component as normal JSF tags

Step 2a: Use Custom Namespace: home.xhtml xmlns:tp="http://java.sun.com/jsf/composite/tutorialspoint">

Step 2b: Use Custom Tag: home.xhtml and pass values

Example Application
TUTORIALS POINT Simply Easy Learning

Page 45

Let us create a test JSF application to test the custom component in JSF. Step 1 2 3 4 5 6 7 8 9 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Create resources folder under src > main folder. Create tutorialspoint folder under src > main > resources folder. Create loginComponent.xhtml file under src > main > resources > tutorialspoint folder. Modify UserData.java file as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

loginComponent.xhtml

#{cc.attrs.usernameLabel} : #{cc.attrs.passwordLabel} :

UserData.java
TUTORIALS POINT Simply Easy Learning

Page 46

package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String login(){ return "result"; } }

home.xhtml

JSF tutorial Custom Component Example

TUTORIALS POINT Simply Easy Learning

Page 47

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 48

14
JSF – Ajax
Ajax: A Brief Introduction
   
AJAX stands for Asynchronous JavaScrict And Xml. Ajax is a technique to use HTTPXMLObject of JavaScript to send data to server and receive data from server asynchronously. So using Ajax technique, javascript code exchanges data with server, updates parts of web page without reloading the whole page. JSF provides execellent support for making ajax call. It provides f:ajax tag to handle ajax calls.

CHAPTER

JSF Tag

Tag Attributes
S.N. 1 Attribute & Description disabled If true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled. event The event that will invoke Ajax requests, for example "click", "change", "blur", "keypress", etc. execute A space-separated List of IDs for components that should be included in the Ajax request. immediate If "true" behavior events generated from this behavior are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase listener An EL expression for a method in a backing bean to be called during the Ajax request. onerror The name of a JavaScript callback function that will be invoked if there is an error during the Ajax request onevent

2 3

4

5

6 7

TUTORIALS POINT Simply Easy Learning

Page 49

The name of a JavaScript callback function that will be invoked to handle UI events. 8 render A space-separated list of IDs for components that will be updated after an Ajax request.

Example Application
Let us create a test JSF application to test the custom component in JSF. Step 1 2 3 4 5 6 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Modify UserData.java file as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

UserData.java package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true) @SessionScoped

public class UserData implements Serializable { private static final long serialVersionUID = 1L; private String name; public String getName() { return name;
}

public void setName(String name) { this.name = name;
}

public String getWelcomeMessage(){ return "Hello " + name;
} }

TUTORIALS POINT Simply Easy Learning

Page 50

home.xhtml

JSF tutorial Ajax Example Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

Enter name and press Show Message button. You will see the following result without page refresh/form submit.

TUTORIALS POINT Simply Easy Learning

Page 51

TUTORIALS POINT Simply Easy Learning

Page 52

15
JSF – Event Handling

CHAPTER

W
   

hen a user clicks a JSF button or link or changes any value in text field, JSF UI component fires event

which will be handled by the the application code. To handle such JSF event, event handler are to be registered in the application code or managed bean. When a UI component checks that a user event has happened, it creates an instance of the corresponding event class and adds it to an event list. Then, Component fires the event, i.e., checks the list of listeners for that event and call the event notification method on each listener or handler. JSF also provide system level event handlers which can be used to do some tasks when application starts or is stopping.

Following are important Event Handler in JSF 2.0: S.N. 1 2 Event Handlers & Description valueChangeListener Value change events get fired when user make changes in input components. actionListener Action events get fired when user clicks on a button or link component. Application Events Events firing during JSF lifecycle: PostConstructApplicationEvent, PreDestroyApplicationEvent , PreRenderViewEvent.

3

(1) valueChangeListener
When user interacts with input components, such as h:inputText or h:selectOneMenu, the JSF fires a valueChangeEvent which can be handled in two ways. Technique Method Binding Description Pass the name of the managed bean method in valueChangeListenerattribute of UI Component.

TUTORIALS POINT Simply Easy Learning

Page 53

ValueChangeListener

Implement ValueChangeListener interface and pass the implementation class name to valueChangeListener attribute of UI Component.

Method Binding
Define a method public void localeChanged(ValueChangeEvent e){ //assign new value to country selectedCountry = e.getNewValue().toString(); } Use above method

onchange="submit()"

ValueChangeListener
Implement ValueChangeListener public class LocaleChangeListener implements ValueChangeListener { @Override public void processValueChange(ValueChangeEvent event) throws AbortProcessingException { //access country bean directly UserData userData = (UserData) FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("userData"); userData.setSelectedCountry(event.getNewValue().toString()); } } Use listener method

Example Application
Let us create a test JSF application to test the valueChangeListener in JSF. Step 1 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in

TUTORIALS POINT Simply Easy Learning

Page 54

the JSF - First Application chapter. 2 3 4 5 6 7 Modify UserData.java file as explained below. Create LocaleChangeListener.java file under a package com.tutorialspoint.test.Modify it as explained below Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

UserData.java package com.tutorialspoint.test; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private static Map countryMap; private String selectedCountry = "United Kingdom"; //default value static{ countryMap = new LinkedHashMap(); countryMap.put("en", "United Kingdom"); //locale, country name countryMap.put("fr", "French"); countryMap.put("de", "German"); } public void localeChanged(ValueChangeEvent e){ //assign new value to country selectedCountry = e.getNewValue().toString(); } public Map getCountries() { return countryMap; } public String getSelectedCountry() { return selectedCountry; } public void setSelectedCountry(String selectedCountry) { this.selectedCountry = selectedCountry;

TUTORIALS POINT Simply Easy Learning

Page 55

} }

LocaleChangeListener.java package com.tutorialspoint.test; import import import import javax.faces.context.FacesContext; javax.faces.event.AbortProcessingException; javax.faces.event.ValueChangeEvent; javax.faces.event.ValueChangeListener;

public class LocaleChangeListener implements ValueChangeListener { @Override public void processValueChange(ValueChangeEvent event) throws AbortProcessingException { //access country bean directly UserData userData = (UserData) FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("userData"); userData.setSelectedCountry(event.getNewValue().toString()); } }

home.xhtml

JSF tutorial valueChangeListener Examples Method Binding
Selected locale :

Country Name:

TUTORIALS POINT Simply Easy Learning

Page 56

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

Select locale. You will see the following result.

Modify home.xhtml again in deployed directory where you've deployed the application as explained below. Keep rest of the files unchanged.

home.xhtml JSF tutorial valueChangeListener Examples ValueChangeListener interface
Selected locale :

Country Name:

Once you are ready with all the changes done, refresh the page in browser. If everything is fine with your application, this will produce following result:

Select locale. You will see the following result.

TUTORIALS POINT Simply Easy Learning

Page 58

(2) actionListener
When user interacts with components, such as h:commandButton or h:link, the JSF fires a action events which can be handled in two ways. Technique Method Binding ActionListener Description Pass the name of the managed bean method in actionListener attribute of UI Component. Implement ActionListener interface and pass the implementation class name to actionListener attribute of UI Component.

Method Binding
Define a method public void updateData(ActionEvent e){ data="Hello World"; } Use above method

ActionListener
TUTORIALS POINT Simply Easy Learning

Page 59

Implement ActionListener public class UserActionListener implements ActionListener{ @Override public void processAction(ActionEvent arg0) throws AbortProcessingException {

//access userData bean directly
UserData userData = (UserData) FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("userData"); userData.setData("Hello World"); } } Use listener method

Example Application
Let us create a test JSF application to test the actionListener in JSF. Step 1 2 3 4 5 6 7 8 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Modify UserData.java file as explained below. Create UserActionListener.java file under a package com.tutorialspoint.test.Modify it as explained below Modify home.xhtml as explained below. Keep rest of the files unchanged. Modify result.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

UserData.java package com.tutorialspoint.test; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent;

TUTORIALS POINT Simply Easy Learning

Page 60

@ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private static Map countryMap; private String data = "sample data"; public String showResult(){ return "result"; } public void updateData(ActionEvent e){ data="Hello World"; } public String getData() { return data; } public void setData(String data) { this.data = data; } }

UserActionListener.java package com.tutorialspoint.test; import import import import javax.faces.context.FacesContext; javax.faces.event.AbortProcessingException; javax.faces.event.ActionEvent; javax.faces.event.ActionListener;

public class UserActionListener implements ActionListener{ @Override public void processAction(ActionEvent arg0) throws AbortProcessingException {

//access userData bean directly
UserData userData = (UserData) FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("userData"); userData.setData("Hello World"); } }

home.xhtml

TUTORIALS POINT Simply Easy Learning

Page 61

JSF tutorial actionListener Examples Method Binding ActionListener interface

result.xhtml

JSF Tutorial! Result
#{userData.data}

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 62

Click on any submit button. You will see the following result.

(3) Application Events

TUTORIALS POINT Simply Easy Learning

Page 63

JSF provides system event listeners to do application specific tasks during JSF application Life Cycle. System Event PostConstructApplicationEvent PreDestroyApplicationEvent PreRenderViewEvent Description Fires when application starts.Can be used to perform initialization tasks after application has started. Fires when application is about to shut down.Can be used to perform a cleanup tasks before application is about to be shut down. Fires before a JSF page is to be displayed. Can be used to authenticate user and provide restricted access to JSF View.

System Events which can be handled in following manner. Technique SystemEventListener Method Binding Description Implement SystemEventListener interface and register the system-eventlistener class in faces-config.xml Pass the name of the managed bean method in listener attribute of f:event.

SystemEventListener
Implement SystemEventListener Interface public class CustomSystemEventListener implements SystemEventListener { @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if(event instanceof PostConstructApplicationEvent){ System.out.println("Application Started. PostConstructApplicationEvent occurred!"); } } } Register custom system event listener for system event in faces-config.xml

com.tutorialspoint.test.CustomSystemEventListener

javax.faces.event.PostConstructApplicationEvent

Method Binding
Define a method public void handleEvent(ComponentSystemEvent event){

TUTORIALS POINT Simply Easy Learning

Page 64

data="Hello World"; } Use above method

Example Application
Let us create a test JSF application to test the system events in JSF. Step 1 2 3 4 5 6 7 8 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Modify UserData.java file as explained below. Create CustomSystemEventListener.java file under a package com.tutorialspoint.test.Modify it as explained below Modify home.xhtml as explained below. Create faces-config.xml in WEB-INF folder.Modify it as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

UserData.java package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ComponentSystemEvent; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private String data = "sample data"; public void handleEvent(ComponentSystemEvent event){ data="Hello World"; }

TUTORIALS POINT Simply Easy Learning

Page 65

public String getData() { return data; } public void setData(String data) { this.data = data; } }

CustomSystemEventListener.java package com.tutorialspoint.test; import javax.faces.application.Application; import javax.faces.event.AbortProcessingException; import javax.faces.event.PostConstructApplicationEvent; import javax.faces.event.PreDestroyApplicationEvent; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; public class CustomSystemEventListener implements SystemEventListener { @Override public boolean isListenerForSource(Object value) {

//only for Application return (value instanceof Application); } @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if(event instanceof PostConstructApplicationEvent){ System.out.println("Application Started.

PostConstructApplicationEvent occurred!"); } if(event instanceof PreDestroyApplicationEvent){ System.out.println("PreDestroyApplicationEvent occurred. Application is stopping."); }
} }

home.xhtml

JSF tutorial

TUTORIALS POINT Simply Easy Learning

Page 66

Application Events Examples
#{userData.data}

faces-config.xhtml

com.tutorialspoint.test.CustomSystemEventListener

javax.faces.event.PostConstructApplicationEvent

com.tutorialspoint.test.CustomSystemEventListener

javax.faces.event.PreDestroyApplicationEvent

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 67

Look into your web-server console output. You will see the following result. INFO: Deploying web application archive helloworld.war Dec 6, 2012 8:21:44 AM com.sun.faces.config.ConfigureListener contextInitialized INFO: Initializing Mojarra 2.1.7 (SNAPSHOT 20120206) for context '/helloworld' Application Started. PostConstructApplicationEvent occurred! Dec 6, 2012 8:21:46 AM com.sun.faces.config.ConfigureListener $WebConfigResourceMonitor$Monitor INFO: Monitoring jndi:/localhost/helloworld/WEB-INF/faces-config.xml for modifications Dec 6, 2012 8:21:46 AM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8080 Dec 6, 2012 8:21:46 AM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 Dec 6, 2012 8:21:46 AM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/24 config=null Dec 6, 2012 8:21:46 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 44272 ms

TUTORIALS POINT Simply Easy Learning

Page 68

16
JSF – JDBC Integration

CHAPTER

I
1 2

n this chapter, we'll demonstrate how to integrate database in JSF using JDBC

Database requirements to run this example S.N. Software & Description PostgreSQL 9.1 Open Source and light weight database PostgreSQL JDBC4 Driver JDBC driver for PostgreSQL 9.1 and JDK 1.5 or above

Put PostgreSQL JDBC4 Driver jar in tomcat web server's lib directory

Database SQL Commands create user user1; create database testdb with owner=user1; CREATE TABLE IF NOT EXISTS authors ( id int PRIMARY KEY, name VARCHAR(25) ); INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO INTO INTO INTO INTO authors(id, authors(id, authors(id, authors(id, authors(id, authors(id, authors(id, authors(id, authors(id, name) name) name) name) name) name) name) name) name) VALUES(1, 'Rob Bal'); VALUES(2, 'John Carter'); VALUES(3, 'Chris London'); VALUES(4, 'Truman De Bal'); VALUES(5, 'Emile Capote'); VALUES(7, 'Breech Jabber'); VALUES(8, 'Bob Carter'); VALUES(9, 'Nelson Mand'); VALUES(10, 'Tennant Mark');

alter user user1 with password 'user1'; grant all on authors to user1;

TUTORIALS POINT Simply Easy Learning

Page 69

Example Application
Let us create a test JSF application to test jdbc integration. Step 1 2 3 4 5 6 7 8 9 10 11 12 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Create resources folder under src > main folder. Create css folder under src > main > resources folder. Create styles.css file under src > main > resources > css folder. Modify styles.css file as explained below. Modify pom.xml as explained below. Create Author.java under package com.tutorialspoint.test as explained below. Create UserData.java under package com.tutorialspoint.test as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

styles.css
.authorTable{ border-collapse:collapse; border-bottom:1px solid #000000; } .authorTableHeader{ text-align:center; background:none repeat scroll 0 0 #B5B5B5; border-bottom:1px solid #000000; border-top:1px solid #000000; padding:2px; } .authorTableOddRow{ text-align:center; background:none repeat scroll 0 0 #FFFFFFF; } .authorTableEvenRow{ text-align:center; background:none repeat scroll 0 0 #D3D3D3; }

pom.xml
TUTORIALS POINT Simply Easy Learning

Page 70

4.0.0 com.tutorialspoint.test helloworld war 1.0-SNAPSHOT helloworld Maven Webapp http://maven.apache.org junit junit 3.8.1 test com.sun.faces jsf-api 2.1.7 com.sun.faces jsf-impl 2.1.7 javax.servlet jstl 1.2 postgresql postgresql 9.1-901.jdbc4 helloworld org.apache.maven.plugins maven-compiler-plugin 2.3.1 1.6 1.6 maven-resources-plugin 2.6 copy-resources validate copy-resources

TUTORIALS POINT Simply Easy Learning

Page 71

${basedir}/target/helloworld/resources src/main/resources true

Author.java package com.tutorialspoint.test; public class Author { int id; String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }

UserData.java package com.tutorialspoint.test; import import import import import import import import java.io.Serializable; java.sql.Connection; java.sql.DriverManager; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.util.ArrayList; java.util.List;

import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ComponentSystemEvent;

TUTORIALS POINT Simply Easy Learning

Page 72

@ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; public List getAuthors(){ ResultSet rs = null; PreparedStatement pst = null; Connection con = getConnection(); String stm = "Select * from authors"; List records = new ArrayList(); try { pst = con.prepareStatement(stm); pst.execute(); rs = pst.getResultSet(); while(rs.next()){ Author author = new Author(); author.setId(rs.getInt(1)); author.setName(rs.getString(2)); records.add(author); } } catch (SQLException e) { e.printStackTrace(); } return records; } public Connection getConnection(){ Connection con = null; String url = "jdbc:postgresql://localhost/testdb"; String user = "user1"; String password = "user1"; try { con = DriverManager.getConnection(url, user, password); System.out.println("Connection completed."); } catch (SQLException ex) { System.out.println(ex.getMessage()); } finally{ } return con; } }

home.xhtml JSF Tutorial!

TUTORIALS POINT Simply Easy Learning

Page 73

Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 74

17
JSF – Spring Integration

CHAPTER

S

pring provides special class DelegatingVariableResolver to integrate JSF and Spring together in seamless

manner. Following steps are required to integrate Spring Dependency Injection (IOC) feature in JSF

Step 1. Add DelegatingVariableResolver
Add a variable-resolver entry in faces-config.xml to point to spring class DelegatingVariableResolver. org.springframework.web.jsf.DelegatingVariableResolver ...

Step 2. Add Context Listeners
Add ContextLoaderListener and RequestContextListener listener provided by spring framework in web.xml ... org.springframework.web.context.ContextLoaderListener org.springframework.web.context.request.RequestContextListener ...

TUTORIALS POINT Simply Easy Learning

Page 75

Step 3. Define Dependency
Define bean(s) in applicationContext.xml which will be used as dependency in managed bean

Step 4. Add Dependency
DelegatingVariableResolver first delegates value lookups to the default resolver of the JSF and then to Spring's WebApplicationContext. This allows one to easily inject spring based dependencies into one's JSF-managed beans. We've injected messageService as spring based dependency here ... userData com.tutorialspoint.test.UserData request messageService #{messageService}

Step 5. Use Dependency
//jsf managed bean public class UserData { //spring managed dependency private MessageService messageService;

public void setMessageService(MessageService messageService) { this.messageService = messageService;
}

public String getGreetingMessage(){ return messageService.getGreetingMessage();
} }

Example Application
Let us create a test JSF application to test spring integration.

TUTORIALS POINT Simply Easy Learning

Page 76

Step 1 2 3 4 5 6 7 8 9 10 11 12

Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Modify pom.xml as explained below. Create faces-config.xml in WEB-INF folder as explained below. Modify web.xml as explained below. Create applicationContext.xml in WEB-INF folder as explained below. Create MessageService.java under package com.tutorialspoint.test as explained below. Create MessageServiceImpl.java under package com.tutorialspoint.test as explained below. Create UserData.java under package com.tutorialspoint.test as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

pom.xml 4.0.0 com.tutorialspoint.test helloworld war 1.0-SNAPSHOT helloworld Maven Webapp http://maven.apache.org junit junit 3.8.1 test com.sun.faces jsf-api 2.1.7 com.sun.faces jsf-impl 2.1.7

TUTORIALS POINT Simply Easy Learning

Page 77

javax.servlet jstl 1.2 org.springframework spring-core 3.1.2.RELEASE org.springframework spring-web 3.1.2.RELEASE helloworld org.apache.maven.plugins maven-compiler-plugin 2.3.1 1.6 1.6 maven-resources-plugin 2.6 copy-resources validate copy-resources ${basedir}/target/helloworld/resources src/main/resources true

faces-config.xml

TUTORIALS POINT Simply Easy Learning

Page 78

org.springframework.web.jsf.DelegatingVariableResolver userData com.tutorialspoint.test.UserData request messageService #{messageService}

web.xml

Archetype Created Web Application javax.faces.PROJECT_STAGE Development org.springframework.web.context.ContextLoaderListener org.springframework.web.context.request.RequestContextListener Faces Servlet javax.faces.webapp.FacesServlet Faces Servlet *.jsf

applicationContext.xml
TUTORIALS POINT Simply Easy Learning

Page 79

MessageService.java package com.tutorialspoint.test; public interface MessageService {
String getGreetingMessage(); }

MessageServiceImpl.java package com.tutorialspoint.test; public class MessageServiceImpl implements MessageService { private String message; public String getGreetingMessage() { return message;
}

public String getMessage() { return message;
}

public void setMessage(String message) { this.message = message;
} }

UserData.java package com.tutorialspoint.test; import java.io.Serializable; public class UserData implements Serializable { private static final long serialVersionUID = 1L; private MessageService messageService; public MessageService getMessageService() { return messageService;

TUTORIALS POINT Simply Easy Learning

Page 80

}

public void setMessageService(MessageService messageService) { this.messageService = messageService;
}

public String getGreetingMessage(){ return messageService.getGreetingMessage();
} }

home.xhtml

JSF Tutorial! Spring Integration Example #{userData.greetingMessage} Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 81

18
JSF – Expression Language

CHAPTER

J
     

SF provides a rich expression language. We can write normal operations using #{operation-expression}

notation. Some of the advantages of JSF Expression languages are following. Can reference bean properties where bean can be a object stored in request, session or application scope or is a managed bean. Provides easy access to elements of a collection which can be a list, map or an array. Provides easy access to predefined objects such as request. Arithmetic, logical, relational operations can be done using expression language. Automatic type conversion. Shows missing values as empty strings instead of NullPointerException.

Example Application
Let us create a test JSF application to test expression language. Step 1 8 9 10 11 12 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Modify UserData.java under package com.tutorialspoint.test as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

UserData.java

TUTORIALS POINT Simply Easy Learning

Page 82

package com.tutorialspoint.test; import java.io.Serializable; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private Date createTime = new Date(); private String message = "Hello World!"; public Date getCreateTime() { return(createTime); } public String getMessage() { return(message); } }

home.xhtml

JSF Tutorial! Expression Language Example Creation time: Message: Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 83

TUTORIALS POINT Simply Easy Learning

Page 84

19
JSF - Internationalization

CHAPTER

I

nternationalization is a technique in which status messages, GUI component labels, currency, date are not

hardcoded in the program instead they are stored outside the source code in resource bundles and retrieved dynamically. JSF provide a very convenient way to handle resource bundle. Following steps are required to internalize a JSF application

Step 1. Define properties files
Create properties file for each locale. Name should be in _.properties format. Default locale can be omitted in file name.

Messages.properties greeting=Hello World!

Messages_fr.properties greeting=Bonjour tout le monde!

Step 2. Update faces-config.xml Faces-config.xml en fr com.tutorialspoint.messages msg

TUTORIALS POINT Simply Easy Learning

Page 85

Step 3. Use resource-bundle var home.xhtml

Example Application
Let us create a test JSF application to test internationalization in JSF. Step 1 2 3 4 5 6 7 8 9 10 11 12 Description Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. Create resources folder under src > main folder. Create com folder under src > main > resources folder. Create tutorialspoint folder under src > main > resources > com folder. Create messages.properties file under src > main > resources > com > tutorialspointfolder.Modify it as explained below Create messages_fr.properties file under src > main > resources > com > tutorialspointfolder.Modify it as explained below Create faces-config.xml in WEB-INF folder as explained below. Create UserData.java under package com.tutorialspoint.test as explained below. Modify home.xhtml as explained below. Keep rest of the files unchanged. Compile and run the application to make sure business logic is working as per the requirements. Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. Launch your web application using appropriate URL as explained below in the last step.

messages.properties greeting=Hello World!

messages_fr.properties greeting=Bonjour tout le monde!

TUTORIALS POINT Simply Easy Learning

Page 86

faces-config.xml en fr com.tutorialspoint.messages msg

UserData.java package com.tutorialspoint.test; import import import import import import import import java.io.Serializable; java.util.LinkedHashMap; java.util.Locale; java.util.Map; javax.faces.bean.ManagedBean; javax.faces.bean.SessionScoped; javax.faces.context.FacesContext; javax.faces.event.ValueChangeEvent;

@ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private String locale; private static Map countries; static{ countries = new LinkedHashMap(); countries.put("English", Locale.ENGLISH); countries.put("French", Locale.FRENCH); } public Map getCountries() { return countries; } public String getLocale() { return locale;

TUTORIALS POINT Simply Easy Learning

Page 87

} public void setLocale(String locale) { this.locale = locale; } //value change event listener public void localeChanged(ValueChangeEvent e){ String newLocaleValue = e.getNewValue().toString(); for (Map.Entry entry : countries.entrySet()) { if(entry.getValue().toString().equals(newLocaleValue)){ FacesContext.getCurrentInstance() .getViewRoot().setLocale((Locale)entry.getValue()); } } } }

home.xhtml JSF tutorial Internalization Language Example Language : Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce following result:

TUTORIALS POINT Simply Easy Learning

Page 88

Change language from dropdown. You will see the following output.

TUTORIALS POINT Simply Easy Learning

Page 89

Similar Documents

Premium Essay

Sample

...DISTRIBUTIONS Simple Random Sample A simple random sample X 1 , , X n , taken from a population represented by a random variable X with mean  and standard deviation  , has the following characteristics.  Each X i , i  1,, n , is a random variable that has the same distribution as X, and thus the same mean  and standard deviation  . The X i ’s are independent random variables implying the following identity:  V  X 1    X n   V  X 1     V  X n    2     2  n 2  The sample mean, X where X  X1    X n , is a continuous random variable n with mean  X   and standard deviation  X  of the mean. Sampling Distribution of the Mean  , known as the standard error n Result 1: If X is Normal, then X is Normal and Z  of the sample n. X   n , regardless of the size Result 2: If n is large enough, n  30 , then X is approximately normal and X  Z , regardless of the distribution of the population random variable X.  n Sampling Distribution of the Proportion For a binomial random variable X with parameters n (sample size) and  (probability of X success or population proportion), the sample proportion is given by p  . n The sample proportion p is a continuous random variable with mean  p   and standard deviation  p   1    n . Result 3: If n is large enough, n  5 and n1     5 , then p is approximately p  normal and Z  .  1    n Why? We want to use the sample mean X to estimate...

Words: 360 - Pages: 2

Premium Essay

Sample Design

...3.1 Research Design 3.2 Sample Design 3.2.1 Target population It would be costly and timely for us to target the whole marketing industry hence we decided to target on specific segment group of UTAR undergraduate students in Sungai Long, Selangor. We study the behavioral respond view of UTAR undergraduate’s students on their perceived on quality, value and satisfaction toward the intention to recommend products or services. According by the Department of the Faculty General Office (FGO), there are estimated 2500 students, thus the recommended sample size is 250 students. With the 95% confidence level and +/-5% margin of error, 264 sets of questionnaire has been distributed to our respondents due to the possibilities of the occurrence of unused data. 3.2.2 Sampling Frame and Sampling Location In our research, we decide to distribute a total of questionnaires which we have prepared early to UTAR undergraduate students in Sungai Long, Selangor. The purpose of the different location chosen is because we want to acquire more precise results. 3.2.3 Sampling Technique Sampling method is a method for investigating a whole population and it includes of probability and non-probability samples. Probability samples are selected to be representative of the population. Then, non-probability is a sampling technique in which units of the sample are selected on the basis of personal judgment or convenience. There are four types of probability sampling techniques; one of them is systematic...

Words: 409 - Pages: 2

Premium Essay

Sample Paper

...Sample Paper Population definitionSuccessful statistical practice is based on focused problem definition. In sampling, this includes defining the population from which our sample is drawn. A population can be defined as including all people or items with the characteristic one wishes to understand. Because there is very rarely enough time or money to gather information from everyone or everything in a population, the goal becomes finding a representative sample (or subset) of that population. Sometimes that which defines a population is obvious. For example, a manufacturer needs to decide whether a batch of material from production is of high enough quality to be released to the customer, or should be sentenced for scrap or rework due to poor quality. In this case, the batch is the population. Although the population of interest often consists of physical objects, sometimes we need to sample over time, space, or some combination of these dimensions. For instance, an investigation of supermarket staffing could examine checkout line length at various times, or a study on endangered penguins might aim to understand their usage of various hunting grounds over time. For the time dimension, the focus may be on periods or discrete occasions. In other cases, our 'population' may be even less tangible. For example, Joseph Jagger studied the behaviour of roulette wheels at a casino in Monte Carlo, and used this to identify a biased wheel. In this case, the 'population' Jagger...

Words: 509 - Pages: 3

Free Essay

Sample Exam

...SAMPLE EXAMINATION The purpose of the following sample examination is to provide an example of what is provided on exam day by ASQ, complete with the same instructions that are provided on exam day. The test questions that appear in this sample examination are retired from the CSSBB pool and have appeared in past CSSBB examinations. Since they are now available to the public, they will NOT appear in future SSBB examinations. This sample examination WILL NOT be allowed into the exam room. Appendix A contains the answers to the sample test questions. ASQ will not provide scoring and analysis for this sample examination. Remember: These test questions will not appear on future examinations so your performance on this sample examination may not reflect how you perform on the formal examination. A self-appraisal of how well you know the content for the specific areas of the body of knowledge (BOK) can be completed by using the worksheet in Appendix B. On page 2 of the instructions, it states “There are 150 questions on this 4-hour examination.” Please note that this sample exam only contains 75 questions. If you have any questions regarding this sample examination, please email cert@asq.org © 2009 ASQ ASQ grants permission for individuals to use this sample examination as a means to prepare for the formal examination. This examination may be printed, reproduced and used for non-commercial, personal or educational purposes only, provided that (i) the examination is not modified...

Words: 4541 - Pages: 19

Free Essay

Sample Essay

...Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample.Sample...

Words: 8977 - Pages: 36

Premium Essay

Sample Size Formula

...Relationship between students’ achievement scores and scores on test anxiety scale (Total scale, Worry Scale and Emotional scale) Aspect N Pearson r Significance Total scale scores and achievement scores 138 - 0.653* 0.000 Worry scale scores and achievement scores 138 - 0.694* 0.000 Emotional scale scores and achievement scores 138 - 0.663* 0.000 It is evident from table 4 that a strong negative and significant relationship exists between students’ achievement scores and Total scale scores as well as on subscales scores. It is also found that achievements is significantly inversely related to both emotional and worry scales as well. The magnitude of the relationship is slightly higher on worry scale as compared to emotionality scale and total score. The range of relationship of each scale is more than 65% which is quite strong in magnitude. This stronger relationship encouraged to further analysis to explore the possibility of test anxiety as a predictor of students’ achievement. Therefore, a Regression analysis was run to explore the cause- effect relationship between achievement scores and test anxiety scale scores. The result is given in table 5. Relationship between Test Anxiety and Academic Achievement Regression analysis Model β t-value Significance Model R square Total anxiety scale scores -0.251 -0.6.700 0.000 Worry scale scores -0.697 -0 4.160 0.000 0.535 Emotional scale scores -0.140 -0.890 ...

Words: 388 - Pages: 2

Premium Essay

Qnt 561 Week 3 Sample Size and Data Collection

...QNT 561 Week 3 Sample Size and Data Collection Follow Below Link to Download Tutorial https://homeworklance.com/downloads/qnt-561-week-3-sample-size-and-data-collection/ For More Information Visit Our Website ( https://homeworklance.com/ ) Email us At: Support@homeworklance.com or lancehomework@gmail.com Sampling and Data Collection Plan – Assessment Activity – Week3 – QNT/561 – eCampus Part 1: Sampling Design Write a 350- to 700-word paper using the scenario and two variables your learning team developed for the Week 2 Business Research Project Part 1 assignment, in which the goal is to submit a random sampling plan in such detail that another researcher could replicate the method. Discuss the following: • Population and size • The target population and brief reasoning • Sampling element which may be conducted through any of the following: o Data mining o Survey (If a survey is chosen, create a 5-10 question document), or o Observation • The sample size • Method of random sampling which may include: o Simple o Stratified o Systematic o Cluster Calculate the sample size for the mean or sample or sample size for the proportion, using a 95% confidence level, estimated population standard deviation or estimate of the true population proportion, and a 5% margin of error. Place the calculation in the Appendix. Discuss how validity and reliability will be achieved. If applicable, explain how human subjects will be protected. Part 2: Data...

Words: 262 - Pages: 2

Premium Essay

Qnt 561 Week 3 Sample Size and Data Collection

...QNT 561 Week 3 Sample Size and Data Collection Click Link Below To Buy: http://hwaid.com/shop/qnt-561-week-3-sample-size-and-data-collection/ QNT 561 Week 3 Sample Size and Data Collection Sampling and Data Collection Plan – Assessment Activity – Week3 – QNT/561 – eCampus Part 1: Sampling Design Write a 350- to 700-word paper using the scenario and two variables your learning team developed for the Week 2 Business Research Project Part 1 assignment, in which the goal is to submit a random sampling plan in such detail that another researcher could replicate the method. Discuss the following: • Population and size • The target population and brief reasoning • Sampling element which may be conducted through any of the following: o Data mining o Survey (If a survey is chosen, create a 5-10 question document), or o Observation • The sample size • Method of random sampling which may include: o Simple o Stratified o Systematic o Cluster Calculate the sample size for the mean or sample or sample size for the proportion, using a 95% confidence level, estimated population standard deviation or estimate of the true population proportion, and a 5% margin of error. Place the calculation in the Appendix. Discuss how validity and reliability will be achieved. If applicable, explain how human subjects will be protected. Part 2: Data Collection Explain how the data will be physically collected. Explain where data will be stored and how it will be protected...

Words: 251 - Pages: 2

Premium Essay

Asbitch as Shit

...Definition of Terms Target population * the population we want to study Sampled population * the population from where we actually select the sample Sample * these are the elements from the sampled population who are actually selected to participate or to be the subject in the study Sample size * Total number of elements in the sample SAMPLING * the process of selecting a small number of elements from a larger defined target group of elements such that the information gathered from the small group will allow judgments to be made about the larger groups SAMPLING TECHNIQUES * PROBABILITY SAMPLING a method of selecting a sample wherein each element in the population has a known, nonzero chance of being included in the sample. Simple Random Sampling a probability sampling method wherein all members of the population have equal chances of being included in the study. When to use: * If the members of the population are not so spread geographically. * If the members are homogeneous with respect to the characteristic under study. Systematic Sampling probability sampling method wherein the selection of the first member (random start - r) is at random (using simple random sampling) and the selection of the other members in sample is systematic by successively taking every kth member from the random start, where k is the sampling interval. When to use: * If the arrangement of the members is according to magnitude...

Words: 820 - Pages: 4

Premium Essay

Sampling

...sampling Cluster sampling is a sampling technique where the entire population is divided into groups, or clusters and a random sample of these clusters are selected. All observations in the selected clusters are included in the sample. Cluster sampling is typically used when the researcher cannot get a complete list of the members of a population they wish to study but can get a complete list of groups or 'clusters' of the population. It is also used when a random sample would produce a list of subjects so widely scattered that surveying them would prove to be far too expensive, for example, people who live in different counties in the Country. Advantages One advantage of cluster sampling is that it is cheap, quick, and easy. Instead of sampling the entire country when using simple random sampling, the research can instead allocate resources to the few randomly selected clusters when using cluster sampling. A second advantage to cluster sampling is that the researcher can have a larger sample size than if he or she was using simple random sampling. Because the researcher will only have to take the sample from a number of clusters, he or she can select more subjects since they are more accessible. Disadvantages One main disadvantage of cluster sampling is that is the least representative of the population out of all the types of probability samples. It is common for individuals within a cluster to have similar characteristics, so when a researcher uses cluster sampling, there...

Words: 1337 - Pages: 6

Premium Essay

Sampling

...size of research population, it is not feasible to test all the individuals of the population since it will take too much time and will be expensive as well. So the researchers take few individuals from the research population ( a subset of the set of target population) using sampling techniques. These techniques helps to take out sample as per the requirements of the type of research that is to be conducted. A research population is also known as a well-defined collection of individuals or objects known to have similar characteristics. All individuals or objects within a certain population usually have a common, binding characteristic or trait. Usually, the description of the population and the common binding characteristic of its members are the same. "Government officials" is a well-defined group of individuals which can be considered as a population and all the members of this population are indeed officials of the government. There are various sources from which a sample is created. A set of all these sources is called a Sampling frame from which the sample is selected. With the help of sampling frames, researchers are able to select the sample population from the target population that will be tested for the research or survey. A sampling frame should have the following characteristics: Completeness: A frame should be complete in a sense that all the individuals of the target population should be covered in the frame. In case we are...

Words: 4006 - Pages: 17

Premium Essay

Sampling Design

...(1) Assign a single number to each element in the sampling frame. – (2) Use random numbers to select elements into the sample until the desired number of cases is obtained. • The method is not very different from winning a lottery. 2. Systematic Sampling • Steps: – (1) Calculate the sampling interval as the ratio between population size and sample size, I = N/n. – (2) Arrange all elements in the population in an order. – (3) Select a case in the first interval randomly. – (4) Select every ith case from this point. 2. Systematic Sampling (continued) I I 1st element, randomly chosen I I I I – Systematic Sampling is easier and simpler than SRS – The text warns of a danger to this method. What is it? 3. Stratified Sampling • Stratified sampling is more complicated than SRS. The advantage is the guaranteed representativeness in some important characteristics. • For example, say that we want to select a sample of 100 individuals. Sex ratio in the sample is up to chance if we do SRS. We can guarantee the 50-50 split if we do stratified sampling: Stratified Sampling, Graphic Representation Population SRS SRS Sample • Stratified sampling is often used to reduce the variability of a sample. Oversampling, Graphic Representation Population SRS SRS Sample • Increasing the representation of a group in a sample. This is often done when groups are very different in size – e.g., race 4. Cluster Sampling • Cluster sampling is...

Words: 921 - Pages: 4

Premium Essay

Pyc3704 Assignment 1

...Assignment One: Data Sheet 1 Kimmy Givins NorthCentral University Dr. Boysen-Rotelli 08/10/2014 Date File 1 Chapter One 1) Determine whether the evaluated group is a population or a sample. a) Based on a randomly selected group of 500 patients with high cholesterol, it was found that 67% have heart disease. Is this a population or a sample; explain your answer. Sample is made up of of the raw data collected from 500 patients which is the sample and 67% is the sample statistics. Bennett, Briggis, & Triola (2009) the raw data is collected from a subnet of patient with high cholesterol (p.3). Which indicate this as a sample from the raw data and sample statistics. b) An investigation of 150 randomly selected local restaurants concluded that 42% of local...

Words: 1907 - Pages: 8

Free Essay

Marketing Research

...All of the following data are demographic data except a. income b. age c. education d. residence e. religion * Data Types The following question elicits _____ data. How satisfied are you with the last flight you took with American Airlines? Very Somewhat Neutral Somewhat Very Dissatisfied Dissatisfied Satisfied Satisfied 1 2 3 4 5 a. demographic b. psychographic c. attitude d. behavioristic Types of variables marketing researchers may work with include all of the following except a. nominal b. ordinal c. logistic d. ratio The variable in which numbers serve only as labels to identify or categorize objects or events is the ____. a. nominal variable b. ordinal variable c. interval variable d. ratio variable The following question will result in a ____ variable. Which is your favorite Yogurt brand? __ Yoplait __ Dannon __ Chobani __ Stonyfield __ Other () a. nominal variable b. ordinal variable c. interval variable d. ratio variable Which type of scale is the following question? Please rank the importance of the following product features in your decision to buy a laptop computer. (1=most important, 4=least important) a. Rank order b. Likert scale ...

Words: 679 - Pages: 3

Premium Essay

Random Sampling Dq

...Simple Random Sampling is done when every individual subject in the population has an equal chance of being selected for the sample, without any bias (Explorable). For example, if a researcher wants to represent the population as a whole, they can pick random numbers or names out a hat or use a program to randomly choose names so the information is not biased. Stratified Sampling is performed by, dividing the population into at least two (or more) groups or sections, which share certain characteristics, called “strata” (Explorable). For example, a researcher who wants to compare the average economic status of different racial groups may use this technique in order to divide the population into groups based on race and ethnicities and then compare the whole average from each ethnic group. Cluster Sampling is done by dividing the population into separate sections or “clusters” and then picks a cluster randomly and chooses all the members from those clusters for the sample (Explorable). For example, using a geographical cluster, in order to look at the academic performance of students. The researcher can divide Nassau County in Long Island into clusters based on the towns. Then, randomly select a certain number of these clusters or towns and include all the students from those clusters to be part of the sample. Systematic Sampling is performed by, using and selecting a point at which to begin and then selecting every x number after that point (Explorable). For example,...

Words: 391 - Pages: 2