JavaServer Faces(JSF)是一個MVC web框架,它使用頁面中可重用的UI組件簡化了基於伺服器的應用程式的用戶界面(UI)的構建。JSF提供了一種將UI小部件與數據源和伺服器端事件處理程序連接起來的工具。JSF規範定義了一組標準UI組件,並爲開發組件提供了一個應用程式編程接口(API)。JSF支持現有標準UI組件的重用和擴展。
Benefits
JSF減少了創建和維護應用程式的工作量,這些應用程式將在Java應用伺服器上運行,並將應用程式UI呈現給目標客戶機。JSF通過−
- Providing 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爲開發人員提供了從UI組件集合中創建Web應用程式的能力,這些UI組件可以以不同的方式呈現多個客戶端類型(例如HTML瀏覽器、無線或WAP設備)。
JSF提供了−
核心庫
一組基本UI組件-標準HTML輸入元素
擴展基本UI組件以創建其他UI組件庫或擴展現有組件
多種呈現功能,使JSF UI組件能夠根據客戶機類型以不同的方式呈現自己
JSF - Environment Setup
本章將指導您如何準備開發環境以開始使用JSF框架。在設置JSF框架之前,您將學習如何在您的機器上設置JDK、Eclipse、Maven和Tomcat。
System Requirement
JSF需要JDK 1.5或更高版本,所以第一個要求是在您的機器上安裝JDK。
JDK | 1.5 or above |
Memory | No minimum requirement |
Disk Space | No minimum requirement |
Operating System | No minimum requirement |
Environment Setup for JSF Application Development
按照給定的步驟設置環境以開始JSF應用程式開發。
Step 1: Verify Java installation on your machine
打開控制台並執行以下Java命令。
OS | Task | Command |
---|---|---|
Windows | Open Command Console | c:\> java -version |
Linux | Open Command Terminal | $ java -version |
Mac | Open Terminal | machine:~ joseph$ java -version |
讓我們驗證所有作業系統的輸出;
OS | Generated Output |
---|---|
Windows | java版本「1.6.0_21」 Java(TM)SE運行時環境(構建1.6.0_21-b07) Java HotSpot(TM)客戶端虛擬機(構建17.0-b17,混合模式,共享) |
Linux | java版本「1.6.0_21」 Java(TM)SE運行時環境(構建1.6.0_21-b07) Java HotSpot(TM)客戶端虛擬機(構建17.0-b17,混合模式,共享) |
Mac | java版本「1.6.0_21」 Java(TM)SE運行時環境(構建1.6.0_21-b07) Java HotSpot(TM)64位伺服器虛擬機(內部版本17.0-b17,混合模式,共享) |
Step 2: Set Up Java Development Kit (JDK)
如果您沒有安裝Java,那麼可以從Oracle的Java站點−Java SE下載中安裝Java軟體開發工具包(SDK)。您將在下載的文件中找到安裝JDK的說明,按照給定的說明安裝和配置安裝程序。最後,將PATH和JAVA_HOME環境變量設置爲引用包含JAVA和javac的目錄,通常分別是JAVA_install_dir/bin和JAVA_install_dir。
將環境變量設置爲指向機器上安裝JAVA的基本目錄位置。
例如−
OS | Output |
---|---|
Windows | Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21 |
Linux | Export JAVA_HOME=/usr/local/java-current |
Mac | Export JAVA_HOME=/Library/Java/Home |
將Java編譯器位置附加到系統路徑。
OS | Output |
---|---|
Windows | Append the string ;%JAVA_HOME%\bin to the end of the system variable, Path. |
Linux | Export PATH=$PATH:$JAVA_HOME/bin/ |
Mac | Not required |
或者,如果您使用集成開發環境(IDE),如Borland JBuilder、Eclipse、IntelliJ IDEA或Sun ONE Studio,請編譯並運行一個簡單的程序,以確認IDE知道您在哪裡安裝了Java。否則,請根據IDE的給定文檔執行正確的設置。
Step 3: Set Up Eclipse IDE
本教程中的所有示例都是使用EclipseIDE編寫的。因此,我們建議您根據作業系統在計算機上安裝最新版本的Eclipse。
要安裝EclipseIDE,請從https://www.Eclipse.org/downloads/>https://www.Eclipse.org/downloads/下載支持WTP的最新Eclipse二進位文件。下載安裝後,將二進位發行版解壓縮到一個方便的位置。例如,在Windows上的C:\ eclipse中,或者在Linux/Unix上的/usr/local/eclipse中,最後適當地設置PATH變量。
Eclipse可以通過在Windows機器上執行以下命令啓動,也可以簡單地雙擊Eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse可以通過在Unix(Solaris、Linux等)機器上執行以下命令來啓動−
$/usr/local/eclipse/eclipse
成功啓動後,如果一切正常,將顯示以下結果。
*注意−使用以下eclipse軟體更新站點將m2eclipse插件安裝到eclipse
m2eclipse插件-https://m2eclipse.sonatype.org/update/。
這個插件允許開發人員在安裝了嵌入式/外部maven的eclipse中運行maven命令。
Step 4: Download Maven archive
從https://Maven.apache.org/Download.html下載Maven 2.2.1
OS | Archive name |
---|---|
Windows | apache-maven-2.0.11-bin.zip |
Linux | apache-maven-2.0.11-bin.tar.gz |
Mac | apache-maven-2.0.11-bin.tar.gz |
Step 5: Extract the Maven archive
將存檔文件解壓縮到要安裝Maven 2.2.1的目錄。子目錄apache-maven-2.2.1將從存檔中創建。
OS | Location (can be different based on your installation) |
---|---|
Windows | C:\Program Files\Apache Software Foundation\apache-maven-2.2.1 |
Linux | /usr/local/apache-maven |
Mac | /usr/local/apache-maven |
Step 6: Set Maven environment variables
將M2_HOME、M2、MAVEN_OPTS添加到環境變量。
OS | Output |
---|---|
Windows | 使用系統屬性設置環境變量。 M2_HOME=C:\程序文件\Apache軟體基金會\apachemaven-2.2.1 M2=%M2\u HOME%\bin MAVEN OPTS=-Xms256m-Xmx512m |
Linux | 打開命令終端並設置環境變量。 將M2導出到HOME=/usr/local/apache maven/apache-maven-2.2.1 導出M2=%M2\u HOME%\bin 導出MAVEN_OPTS=-Xms256m-Xmx512m |
Mac | 打開命令終端並設置環境變量。 將M2導出到HOME=/usr/local/apache maven/apache-maven-2.2.1 導出M2=%M2\u HOME%\bin 導出MAVEN_OPTS=-Xms256m-Xmx512m |
Step 7: Add Maven bin directory location to system path
現在將M2變量附加到系統路徑。
OS | Output |
---|---|
Windows | Append the string ;%M2% to the end of the system variable, Path. |
Linux | export PATH=$M2:$PATH |
Mac | export PATH=$M2:$PATH |
Step 8: Verify Maven installation.
打開控制台,執行以下mvn命令。
OS | Task | Command |
---|---|---|
Windows | Open Command Console | c:\> mvn --version |
Linux | Open Command Terminal | $ mvn --version |
Mac | Open Terminal | machine:~ joseph$ mvn --version |
最後,驗證上述命令的輸出,如下表所示。
OS | Output |
---|---|
Windows | 阿帕奇馬文2.2.1(r801777;2009-08-07 00:46:01+0530) Java版本:1.6.0_21 Java home:C:程序文件JavaJDK1.6.0 u 21jre |
Linux | 阿帕奇馬文2.2.1(r801777;2009-08-07 00:46:01+0530) Java版本:1.6.0_21 Java home:C:程序文件JavaJDK1.6.0 u 21jre |
Mac | 阿帕奇馬文2.2.1(r801777;2009-08-07 00:46:01+0530) Java版本:1.6.0_21 Java home:C:程序文件JavaJDK1.6.0 u 21jre |
Step 9: Set Up Apache Tomcat
您可以從https://Tomcat.apache.org/「target=」\blank「>https://Tomcat.apache.org/下載最新版本的Tomcat。下載安裝後,將二進位發行版解壓縮到一個方便的位置。例如,在Windows上的C:\ apache-tomcat-6.0.33或Linux/Unix上的/usr/local/apache-tomcat-6.0.33中,將CATALINA_HOME環境變量設置爲指向安裝位置。
Tomcat可以通過在Windows機器上執行以下命令來啓動,也可以雙擊startup.bat
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-6.0.33\bin\startup.bat
Tomcat可以通過在Unix(Solaris、Linux等)機器上執行以下命令來啓動。
$CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-6.0.33/bin/startup.sh
成功啓動後,通過訪問http://localhost:8080/可以使用Tomcat中包含的默認web應用程式。如果一切正常,它將顯示以下結果。
有關配置和運行Tomcat的更多信息,可以在這裡的文檔中找到,也可以在Tomcat網站−http://Tomcat.apache.org上找到
可以通過在Windows機器上執行以下命令來停止Tomcat。
%CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat可以通過在Unix(Solaris、Linux等)機器上執行以下命令來停止。
$CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
JSF - Architecture
JSF技術是一個用於開發、構建伺服器端用戶界面組件並在web應用程式中使用它們的框架。JSF技術基於模型-視圖-控制器(MVC)體系結構,用於將邏輯與表示分離。
What is MVC Design Pattern?
MVC設計模式使用三個獨立的模塊設計應用程式;
S.No | Module & Description |
---|---|
1 | 模型 攜帶數據並登錄 |
2 | 查看 顯示用戶界面 |
3 | 控制器 處理應用程式的處理。 |
MVC設計模式的目的是將模型和表示分離,使開發人員能夠更清晰地關注其核心技能和協作。
網頁設計師必須只關注視圖層,而不是模型和控制器層。開發人員可以更改模型的代碼,通常不需要更改視圖層。控制器用於處理用戶操作。在此過程中,圖層模型和視圖可能會更改。
JSF Architecture
JSF應用程式類似於任何其他基於Java技術的web應用程式;它運行在Java servlet容器中,並且包含−
JavaBeans組件作爲模型包含特定於應用程式的功能和數據
用於表示事件處理程序和驗證器的自定義標記庫
用於呈現UI組件的自定義標記庫
在伺服器上表示爲有狀態對象的UI組件
伺服器端幫助程序類
驗證程序、事件處理程序和導航處理程序
用於配置應用程式資源的應用程式配置資源文件
有些控制器可用於執行用戶操作。UI可以由web頁面作者創建,業務邏輯可以由託管bean使用。
JSF提供了幾種呈現單個組件的機制。由web頁面設計器來選擇所需的表示,應用程式開發人員不需要知道使用哪種機制來呈現JSF UI組件。
JSF - Life Cycle
JSF應用程式的生命周期由以下六個階段組成;
- 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
這六個階段顯示了JSF處理表單的順序。該列表按可能的執行順序顯示各個階段,並在每個階段進行事件處理。
Phase 1: Restore view
只要單擊連結或按鈕並且JSF收到請求,JSF就開始恢復視圖階段。
在此階段,JSF構建視圖,將事件處理程序和驗證器連接到UI組件,並將視圖保存在FacesContext實例中。FacesContext實例現在將包含處理請求所需的所有信息。
Phase 2: Apply request values
創建/恢復組件樹後,組件樹中的每個組件都使用decode方法從請求參數中提取其新值。組件存儲此值。如果轉換失敗,將生成一條錯誤消息並在FacesContext上排隊。此消息將在呈現響應階段顯示,同時顯示所有驗證錯誤。
如果在當前FacesContext實例上有任何名爲render response的decode methods事件偵聽器,JSF將移動到render response階段。
Phase 3: Process validation
在此階段,JSF處理組件樹上註冊的所有驗證器。它檢查組件屬性規則以進行驗證,並將這些規則與爲組件存儲的本地值進行比較。
如果本地值無效,JSF將向FacesContext實例添加一條錯誤消息,生命周期將進入呈現響應階段,並再次顯示帶有錯誤消息的同一頁。
Phase 4: Update model values
在JSF檢查數據是否有效之後,它遍歷組件樹並將相應的伺服器端對象屬性設置爲組件的本地值。JSF將更新與輸入組件的value屬性對應的bean屬性。
如果在當前FacesContext實例上有任何名爲render response的updateModels方法,JSF將移動到render response階段。
Phase 5: Invoke application
在此階段,JSF處理任何應用程式級事件,例如提交表單/連結到另一個頁面。
Phase 6: Render response
在此階段,如果應用程式使用JSP頁面,JSF會要求容器/應用伺服器呈現頁面。對於初始請求,當JSP容器執行頁面時,頁面上表示的組件將被添加到組件樹中。如果這不是一個初始請求,則組件樹已經生成,因此不需要再次添加組件。在這兩種情況下,當JSP容器/應用伺服器遍歷頁面中的標記時,組件將呈現它們自己。
呈現視圖的內容後,將保存響應狀態,以便後續請求可以訪問它,並可用於還原視圖階段。
JSF - First Application
爲了創建一個簡單的JSF應用程式,我們將使用maven原型webapp插件。在下面的示例中,我們將在C:\ JSF文件夾中創建一個基於maven的web應用程式項目。
Create Project
打開command console,轉到JSFC:\>目錄並執行下面的mvn命令。
C:\JSF>mvn archetype:create -DgroupId = com.tutorialspoint.test -DartifactId = helloworld -DarchetypeArtifactId = maven-archetype-webapp
Maven將開始處理並創建完整的java web應用程式項目結構。
[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] ------------------------------------------------------------- [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] -------------------------------------------------------------
現在轉到C:/JSF目錄。您將看到創建了一個名爲helloworld的Java web應用程式項目(在artifactId中指定)。Maven使用標準的目錄布局,如下面的螢幕截圖所示。
通過上面的例子,我們可以理解以下關鍵概念。
S.No | Folder Structure & Description |
---|---|
1 | 地獄世界 包含src folder和pom.xml |
2 | SRC/MAN/WEPAPP 包含WEB-INF文件夾和index.jsp頁 |
3 | src//main//resources/ 它包含圖像/屬性文件(在上面的例子中,我們需要手動創建這個結構) |
Add JSF Capability to Project
添加以下JSF依賴項。
<dependencies> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> </dependencies>
Complete POM.xml
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.test</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
Prepare Eclipse Project
讓我們打開命令控制台。轉到C:\>JSF>helloworld目錄並執行以下mvn命令。
C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0
Maven將開始處理,創建eclipse就緒項目,並添加wtp功能。
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 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
以下是步驟&負;
使用導入嚮導在eclipse中導入項目。
轉到文件導入。。。&工作區中的現有項目。
選擇根目錄到helloworld。
將項目複製到要檢查的工作區中。
單擊「完成」按鈕。
Eclipse將在其工作區中導入和複製項目C:\→Projects→Data→workspace。
Configure Faces Servlet in web.xml
在webapp→web-INF文件夾中找到web.xml並按如下所示更新它。
<?xml version = "1.0" encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version="2.5"> <welcome-file-list> <welcome-file>faces/home.xhtml</welcome-file> </welcome-file-list> <!-- FacesServlet is main servlet responsible to handle all request. It acts as central controller. This servlet initializes the JSF components before the JSP is displayed. --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>
Create a Managed Bean
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
在webapp文件夾下創建一個page home.xhtml。更新home.xhtml的代碼,如下所示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> #{helloWorld.getMessage()} </body> </html>
Build the Project
以下是步驟。
在eclipse中選擇helloworld項目
使用運行方式嚮導
選擇Run As→Maven包
Maven將開始構建項目,並在C:\→Projects→Data→WorkSpace→helloworld→target文件夾下創建helloworld.war。
[INFO] Scanning for projects... [INFO] ----------------------------------------------------- [INFO] Building helloworld Maven Webapp [INFO] [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] ------------------------------------------------ [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
以下是步驟。
停止tomcat伺服器。
將helloworld.war文件複製到tomcat安裝目錄→webapps文件夾。
啓動tomcat伺服器。
在webapps目錄中,應該有一個helloworld創建的文件夾。
現在helloworld.war已經成功地部署在Tomcat Webserver根目錄中。
Run Application
在web瀏覽器中輸入url:http://localhost:8080/helloworld/home.jsf以啓動應用程式。
伺服器名(localhost)和埠(8080)可能因tomcat配置而異。
JSF - Managed Beans
託管Bean是用JSF註冊的常規javabean類。換句話說,託管bean是由JSF框架管理的javabean。託管bean包含getter和setter方法、業務邏輯,甚至支持bean(bean包含所有HTML表單值)。
託管bean用作UI組件的模型。可以從JSF頁面訪問託管Bean。
在JSF 1.2中,託管bean必須在JSF配置文件(如facesconfig.xml)中註冊它。從JSF 2.0開始,託管bean可以很容易地使用注釋註冊。這種方法將bean及其註冊保存在一個地方,因此更易於管理。
Using XML Configuration
<managed-bean> <managed-bean-name>helloWorld</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> <managed-bean> <managed-bean-name>message</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
Using Annotation
@ManagedBean(name = "helloWorld", eager = true) @RequestScoped public class HelloWorld { @ManagedProperty(value = "#{message}") private Message message; ... }
@ManagedBean Annotation
@managed bean用name屬性中指定的名稱將bean標記爲託管bean。如果沒有指定name屬性,則託管bean名稱將默認爲完全限定類名的類名部分。在我們的情況下,那就是地獄。
另一個重要的屬性是急切。如果eager=「true」,則在首次請求之前創建託管bean,否則將使用「惰性」初始化,其中只有在請求時才會創建bean。
Scope Annotations
作用域注釋設置託管bean將被放置到的作用域。如果未指定作用域,則bean將默認爲請求作用域。下表簡要討論了每個範圍。
S.No | Scope & Description |
---|---|
1 | @請求範圍 Bean的生命周期與HTTP請求響應的生命周期一樣長。它根據HTTP請求創建,並在與HTTP請求關聯的HTTP響應完成時被銷毀。 |
2 | @非範圍 Bean的壽命與一個EL評估一樣長。它在EL評估後創建,並在EL評估後立即銷毀。 |
3 | @視域 只要用戶在瀏覽器窗口/選項卡中與同一個JSF視圖交互,Bean就會存在。它根據HTTP請求創建,並在用戶回發到其他視圖時被銷毀。 |
4 | @會議範圍 Bean的壽命與HTTP會話的壽命一樣長。它在會話中涉及此bean的第一個HTTP請求時創建,並在HTTP會話無效時被銷毀。 |
5 | @應用範圍 Bean的壽命與web應用程式的壽命一樣長。它是在應用程式中涉及這個bean的第一個HTTP請求時(或者當web應用程式啓動並且在@ManagedBean中設置eager=true屬性時)創建的,並在web應用程式關閉時被銷毀。 |
6 | @自定義範圍 Bean的生命周期與爲這個作用域創建的自定義映射中的Bean條目的生命周期一樣長。 |
@ManagedProperty Annotation
JSF是一個簡單的靜態依賴注入(DI)框架。使用@managed property注釋,可以在另一個託管bean中注入託管bean的屬性。
Example Application
讓我們創建一個測試JSF應用程式來測試託管bean的上述注釋。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - Create Application chapter. |
2 | Modify HelloWorld.java as explained below. Keep the rest of the files unchanged. |
3 | Create Message.java under a package com.tutorialspoint.test as explained below. |
4 | Compile and run the application to make sure business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | 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 { private String message = "Hello World!"; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
home.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> #{helloWorld.message} </body> </html>
完成所有更改後,讓我們像在JSF-創建應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Page Navigation
導航規則是JSF框架提供的那些規則,用於描述單擊按鈕或連結時要顯示哪個視圖。
導航規則可以在JSF配置文件faces-config.xml中定義。它們可以在託管bean中定義。
導航規則可以包含顯示結果視圖的條件。JSF 2.0還提供了隱式導航,無需定義導航規則。
Implicit Navigation
JSF 2.0提供了名爲隱式導航的自動查看頁面解析器機制。在這種情況下,您只需要將視圖名放在action屬性中,JSF將在部署的應用程式中自動搜索正確的視圖頁面。
Auto Navigation in JSF Page
在任何JSF UI組件的action屬性中設置視圖名。
<h:form> <h3>Using JSF outcome</h3> <h:commandButton action = "page2" value = "Page2" /> </h:form>
在這裡,當點擊Page2按鈕時,JSF將解析視圖名,Page2作爲Page2.xhtml擴展名,並在當前目錄中找到相應的視圖文件Page2.xhtml。
Auto Navigation in Managed Bean
在託管bean中定義方法以返回視圖名稱。
@ManagedBean(name = "navigationController", eager = true) @RequestScoped public class NavigationController implements Serializable { public String moveToPage1() { return "page1"; } }
使用託管bean獲取任何JSF UI組件的action屬性中的視圖名。
<h:form> <h3> Using Managed Bean</h3> <h:commandButton action = "#{navigationController.moveToPage1}" value = "Page1" /glt; </h:form>
在這裡,當點擊Page1按鈕時,JSF將解析視圖名,Page1作爲Page1.xhtml擴展名,並在當前目錄中找到相應的視圖文件Page1.xhtml。
Conditional Navigation
使用託管bean,我們可以很容易地控制導航。查看託管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, //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.
<h:form> <h:commandLink action = "#{navigationController.showPage}" value = "Page1"> <f:param name = "pageId" value = "1" /> </h:commandLink> <h:commandLink action = "#{navigationController.showPage}" value = "Page2"> <f:param name = "pageId" value = "2" /> </h:commandLink> <h:commandLink action = "#{navigationController.showPage}" value = "Home"> <f:param name = "pageId" value = "3" /> </h:commandLink> </h:form>
Here, when "Page1" button is clicked.
JSF將創建參數pageId=1的請求
然後JSF將把這個參數傳遞給navigationController的託管屬性pageId
現在調用navigationController.showPage(),它將在檢查pageId之後返回視圖page1
JSF將把視圖名page1解析爲page1.xhtml擴展名
在當前目錄中找到相應的視圖文件page1.xhtml
Resolving Navigation Based on from-action
即使託管bean的不同方法返回相同的視圖名,JSF也提供導航解析選項。
查看託管bean中的以下代碼。
public String processPage1() { return "page"; } public String processPage2() { return "page"; }
要解析視圖,請在faces-config.xml中定義以下導航規則
<navigation-rule> <from-view-id>home.xhtml</from-view-id> <navigation-case> <from-action>#{navigationController.processPage1}</from-action> <from-outcome>page</from-outcome> <to-view-id>page1.jsf</to-view-id> </navigation-case> <navigation-case> <from-action>#{navigationController.processPage2}</from-action> <from-outcome>page</from-outcome> <to-view-id>page2.jsf</to-view-id> </navigation-case> </navigation-rule>
這裡,單擊Page1按鈕時−
調用navigationController.processPage1(),它將以頁的形式返回視圖
JSF將解析視圖名,page1因爲視圖名是page,而從faces config中的action中解析的是navigationController.processPage1
在當前目錄中找到相應的視圖文件page1.xhtml
Forward vs Redirect
默認情況下,JSF在導航到另一個頁面時執行伺服器頁面轉發,應用程式的URL不會更改。
要啓用頁面重定向,請在視圖名稱的末尾附加faces redirect=true。
<h:form> <h3>Forward</h3> <h:commandButton action = "page1" value = "Page1" /> <h3>Redirect</h3> <h:commandButton action = "page1?faces-redirect = true" value = "Page1" /> </h:form>
在這裡,單擊Forward下的Page1按鈕,將得到以下結果。
單擊「重定向」下的「第1頁」按鈕時,將得到以下結果。
Example Application
讓我們創建一個測試JSF應用程式來測試上述所有導航示例。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - Create Application chapter. |
2 | Create NavigationController.java under a package com.tutorialspoint.test as explained below. |
3 | Create faces-config.xml under a WEB-INF folder and updated its contents as explained below. |
4 | Update web.xml under a WEB-INF folder as explained below. |
5 | Create page1.xhtml and page2.xhtml and modify home.xhtml under a webapp folder as explained below. |
6 | Compile and run the application to make sure business logic is working as per the requirements. |
7 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
8 | 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; @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
<?xml version = "1.0" encoding = "UTF-8"?> <faces-config xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version = "2.0"> <navigation-rule> <from-view-id>home.xhtml</from-view-id> <navigation-case> <from-action>#{navigationController.processPage1}</from-action> <from-outcome>page</from-outcome> <to-view-id>page1.jsf</to-view-id> </navigation-case> <navigation-case> <from-action>#{navigationController.processPage2}</from-action> <from-outcome>page</from-outcome> <to-view-id>page2.jsf</to-view-id> </navigation-case> </navigation-rule> </faces-config>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value>/WEB-INF/faces-config.xml</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> </web-app>
page1.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html"> <h:body> <h2>This is Page1</h2> <h:form> <h:commandButton action = "home?faces-redirect = true" value = "Back To Home Page" /> </h:form> </h:body> </html>
page2.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html"> <h:body> <h2>This is Page2</h2> <h:form> <h:commandButton action = "home?faces-redirect = true" value = "Back To Home Page" /> </h:form> </h:body> </html>
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:body> <h2>Implicit Navigation</h2> <hr /> <h:form> <h3>Using Managed Bean</h3> <h:commandButton action = "#{navigationController.moveToPage1}" value = "Page1" /> <h3>Using JSF outcome</h3> <h:commandButton action = "page2" value = "Page2" /> </h:form> <br/> <h2>Conditional Navigation</h2> <hr /> <h:form> <h:commandLink action = "#{navigationController.showPage}" value="Page1"> <f:param name = "pageId" value = "1" /> </h:commandLink> <h:commandLink action = "#{navigationController.showPage}" value="Page2"> <f:param name = "pageId" value = "2" /> </h:commandLink> <h:commandLink action = "#{navigationController.showPage}" value = "Home"> <f:param name = "pageId" value = "3" /> </h:commandLink> </h:form> <br/> <h2>"From Action" Navigation</h2> <hr /> <h:form> <h:commandLink action = "#{navigationController.processPage1}" value = "Page1" /> <h:commandLink action = "#{navigationController.processPage2}" value = "Page2" /> </h:form> <br/> <h2>Forward vs Redirection Navigation</h2> <hr /> <h:form> <h3>Forward</h3> <h:commandButton action = "page1" value = "Page1" /> <h3>Redirect</h3> <h:commandButton action = "page1?faces-redirect = true" value = "Page1" /> </h:form> </h:body> </html>
完成所有更改後,讓我們像在JSF-創建應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Basic Tags
在本章中,您將了解各種類型的基本JSF標記。
JSF提供了一個標準的HTML標記庫。這些標記被呈現到相應的html輸出中。
對於這些標記,您需要在html節點中使用以下URI名稱空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html">
以下是JSF 2.0中重要的基本標記。
S.No | Tag & Description |
---|---|
1 | h:inputText
Renders a HTML Input of Type=「」Text Box,Text Box. |
2 | h:inputSecret
呈現文本框類型爲「password」的HTML輸入。 |
3 | h:inputTextarea
由HTML文本區域欄位呈現。 |
4 | h:inputHidden
呈現類型爲「hidden」的HTML輸入。 |
5 | h:selectBooleanCheckbox
呈現單個HTML複選框。 |
6 | h:selectManyCheckbox
呈現一組HTML複選框。 |
7 | h:selectOneRadio
由單個HTML單選按鈕呈現。 |
8 | h:selectOneListbox
呈現HTML單個列表框。 |
9 | h:selectManyListbox
呈現HTML多重列表框。 |
10 | h:selectOneMenu
「由HTML定向」組合框。 |
11 | h:outputText
由HTML文本指導。 |
12 | h:outputFormat
由HTML文本指導。 It accepts parameters. |
13 | h:graphicImage
渲染圖像。 |
14 | h:outputStylesheet
在HTML輸出中包含CSS樣式表。 |
15 | h:outputScript
在HTML輸出中包含腳本。 |
16 | h:commandButton
呈現類型爲「提交」按鈕的HTML輸入。 |
17 | h:Link
由HTML錨定向。 |
18 | h:commandLink
由HTML錨定向。 |
19 | h:outputLink
由HTML錨定向。 |
20 | h:panelGrid
以網格的形式呈現HTML表。 |
21 | h:message
呈現JSF UI組件的消息。 |
22 | h:messages
呈現JSF UI組件的所有消息。 |
23 | f:param
將參數傳遞給JSF UI組件。 |
24 | f:attribute
將屬性傳遞給JSF UI組件。 |
25 | f:setPropertyActionListener
設置託管bean屬性的值。 |
JSF - Facelets Tags
JSF提供了特殊的標記來爲一個名爲facelets標記的web應用程式創建公共布局。這些標記提供了在一個位置管理多個頁面的公共部分的靈活性。
對於這些標記,需要在html節點中使用以下URI名稱空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets">
以下是JSF 2.0中的重要Facelets標記。
S.No | Tag & Description |
---|---|
1 | Templates
我們將演示如何使用以下標記使用模板
|
2 | Parameters
我們將演示如何使用以下標記將參數傳遞到模板文件
|
3 | Custom
我們將演示如何創建自定義標記 |
4 | Remove
我們將演示從生成的HTML頁面中刪除JSF代碼的能力 |
JSF - Convertor Tags
JSF提供了內置的轉換器,將其UI組件的數據轉換爲託管bean中使用的對象,反之亦然。例如,這些標記可以將文本轉換爲日期對象,還可以驗證輸入的格式。
對於這些標記,需要在html節點中使用以下URI名稱空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core">
以下是JSF 2.0&minus中重要的Convertor標記;
S.No | Tag & Description |
---|---|
1 | f:convertNumber
將字符串轉換爲所需的多種格式 |
2 | f:convertDateTime
將字符串轉換爲所需格式的日期 |
3 | Custom Convertor
創建自定義轉換器 |
JSF - Validator Tags
JSF提供了內置的驗證器來驗證其UI組件。這些標記可以驗證欄位的長度,即可以是自定義對象的輸入類型。
對於這些標記,您需要在html節點中使用以下URI名稱空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core">
以下是JSF 2.0中的重要驗證器標記−
S.No | Tag & Description |
---|---|
1 | f:validateLength
驗證字符串的長度 |
2 | f:validateLongRange
驗證數值的範圍 |
3 | f:validateDoubleRange
驗證浮點值的範圍 |
4 | f:validateRegex
使用給定的正則表達式驗證JSF組件 |
5 | Custom Validator
創建自定義驗證器 |
JSF - DataTable
JSF提供了一個名爲DataTable的富控制項來呈現和格式化html表。
DataTable可以遍歷值的集合或數組來顯示數據。
DataTable提供屬性,以方便地修改其數據。
HTML Header
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html"> </html>
以下是JSF 2.0中的重要數據表操作−
S.No | Tag & Description |
---|---|
1 | Display DataTable
如何顯示數據表 |
2 | Add data
如何在數據表中添加新行 |
3 | Edit data
如何編輯數據表中的行 |
4 | Delete data
如何刪除數據表中的行 |
5 | Using DataModel
使用數據模型顯示數據表中的行號 |
JSF - Composite Components
JSF爲開發人員提供了強大的功能來定義自己的自定義組件,這些組件可用於呈現自定義內容。
Define Custom Component
在JSF中定義自定義組件是一個兩步過程。
Step | Description |
---|---|
1a | 創建資源文件夾。 在resources文件夾中創建一個具有複合命名空間的xhtml文件。 |
1b | 使用複合標記composite:interface、composite:attribute和composite:implementation來定義複合組件的內容。使用composite:implementation中的cc.attrs獲取使用composite:interface中的composite:attribute定義的變量。 |
Step 1a: Create Custom Component : loginComponent.xhtml
在html頭中使用複合命名空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:composite = "http://java.sun.com/jsf/composite"> ... </html>
Step 1b: Use Composite Tags : loginComponent.xhtml
下表介紹了複合標記的使用。
S.No | Tag & Description |
---|---|
1 | 複合:界面 聲明要在composite:implementation中使用的可配置值。 |
2 | 合成:屬性 使用此標記聲明配置值。 |
3 | 組合:實現 聲明JSF組件。可以使用{cc.attrs.attribute name}表達式訪問composite:interface中定義的可配置值。 |
<composite:interface> <composite:attribute name = "usernameLabel" /> <composite:attribute name = "usernameValue" /> </composite:interface> <composite:implementation> <h:form> #{cc.attrs.usernameLabel} : <h:inputText id = "username" value = "#{cc.attrs.usernameValue}" /> </h:form>
Use Custom Component
在JSF中使用自定義組件是一個簡單的過程。
Step | Description |
---|---|
2a | Create a xhtml file and use custom component's namespace. Namespace will the http://java.sun.com/jsf/<folder-name> where folder-name is folder in resources directory containing the custom component |
2b | Use the custom component as normal JSF tags |
Step 2a: Use Custom Namespace: home.xhtml
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint">
Step 2b: Use Custom Tag: home.xhtml and Pass Values
<h:form> <tp:loginComponent usernameLabel = "Enter User Name: " usernameValue = "#{userData.name}" /> </h:form>
Example Application
讓我們創建一個測試JSF應用程式來測試JSF中的自定義組件。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → main folder. |
3 | Create tutorialspoint folder under src → main → resources folder. |
4 | Create loginComponent.xhtml file under src → main → resources → tutorialspoint folder. |
5 | Modify UserData.java file as explained below. |
6 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
7 | Compile and run the application to make sure the business logic is working as per the requirements. |
8 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
9 | Launch your web application using appropriate URL as explained below in the last step. |
loginComponent.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:composite = "http://java.sun.com/jsf/composite"> <composite:interface> <composite:attribute name = "usernameLabel" /> <composite:attribute name = "usernameValue" /> <composite:attribute name = "passwordLabel" /> <composite:attribute name = "passwordValue" /> <composite:attribute name = "loginButtonLabel" /> <composite:attribute name = "loginButtonAction" method-signature = "java.lang.String login()" /> </composite:interface> <composite:implementation> <h:form> <h:message for = "loginPanel" style = "color:red;" /> <h:panelGrid columns = "2" id = "loginPanel"> #{cc.attrs.usernameLabel} : <h:inputText id = "username" value = "#{cc.attrs.usernameValue}" /> #{cc.attrs.passwordLabel} : <h:inputSecret id = "password" value = "#{cc.attrs.passwordValue}" /> </h:panelGrid> <h:commandButton action = "#{cc.attrs.loginButtonAction}" value = "#{cc.attrs.loginButtonLabel}"/> </h:form> </composite:implementation> </html>
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; 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
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>Custom Component Example</h2> <h:form> <tp:loginComponent usernameLabel = "Enter User Name: " usernameValue = "#{userData.name}" passwordLabel = "Enter Password: " passwordValue = "#{userData.password}" loginButtonLabel = "Login" loginButtonAction = "#{userData.login}" /> </h:form> </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Ajax
AJAX代表異步JavaScript和Xml。
Ajax是一種使用JavaScript的HTTPXMLObject向伺服器發送數據並異步從伺服器接收數據的技術。因此,使用Ajax技術,javascript代碼與伺服器交換數據,更新web頁面的部分內容,而無需重新加載整個頁面。
JSF爲發出ajax調用提供了execellent支持。它提供了f:ajax標記來處理ajax調用。
JSF Tag
<f:ajax execute = "input-component-name" render = "output-component-name" />
Tag Attributes
S.No | Attribute & Description |
---|---|
1 | 殘疾人 如果爲true,Ajax行爲將應用於任何父組件或子組件。如果爲false,則將禁用Ajax行爲。 |
2 | 事件 調用Ajax請求的事件,例如「click」、「change」、「blur」、「keypress」等。 |
3 | 執行 應包含在Ajax請求中的組件的id的空格分隔列表。 |
4 | 立即 如果在此行爲生成的「真」行爲事件在應用請求值階段廣播。否則,事件將在調用應用程式階段廣播。 |
5 | 聽者 在Ajax請求期間調用的後備be An中方法的EL表達式。 |
6 | 誤差 如果在Ajax請求期間出現錯誤,將調用的JavaScript回調函數的名稱。 |
7 | 一個事件 將被調用以處理UI事件的JavaScript回調函數的名稱。 |
8 | 渲染 將在Ajax請求後更新的組件的id的空格分隔列表。 |
Example Application
讓我們創建一個測試JSF應用程式來測試JSF中的自定義組件。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Modify UserData.java file as explained below. |
3 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
4 | Compile and run the application to make sure the business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | 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; } }
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>Ajax Example</h2> <h:form> <h:inputText id = "inputName" value = "#{userData.name}"></h:inputText> <h:commandButton value = "Show Message"> <f:ajax execute = "inputName" render = "outputMessage" /> </h:commandButton> <h2><h:outputText id = "outputMessage" value = "#{userData.welcomeMessage != null ? userData.welcomeMessage : ''}" /></h2> </h:form> </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
輸入名稱並按「顯示消息」按鈕。在沒有頁面刷新/表單提交的情況下,您將看到以下結果。
JSF - Event Handling
當用戶單擊JSF按鈕或連結或更改文本欄位中的任何值時,JSF UI組件將觸發一個事件,該事件將由應用程式代碼處理。要處理此類事件,需要在應用程式代碼或託管be an中註冊事件處理程序。
當UI組件檢查用戶事件是否已發生時,它將創建相應事件類的實例並將其添加到事件列表中。然後,組件觸發事件,即檢查該事件的偵聽器列表,並對每個偵聽器或處理程序調用事件通知方法。
JSF還提供了系統級事件處理程序,可以在應用程式啓動或停止時使用這些處理程序執行某些任務。
以下是JSF 2.0&minus中一些重要的事件處理程序;
S.No | Event Handlers & Description |
---|---|
1 | valueChangeListener
當用戶在輸入組件中進行更改時,將觸發值更改事件。 |
2 | actionListener
當用戶單擊按鈕或連結組件時,將觸發操作事件。 |
3 | Application Events
在JSF生命周期中觸發的事件:PostConstructApplicationEvent、PreDestroyApplicationEvent、PreRenderViewEvent。 |
JSF - JDBC Integration
在本文中,我們將演示如何使用JDBC在JSF中集成資料庫。
下面是運行此示例的資料庫要求。
S.No | Software & Description |
---|---|
1 | PostgreSQL 9.1
開源輕量級資料庫 |
2 | PostgreSQL JDBC4 Driver
PostgreSQL 9.1和JDK 1.5或更高版本的JDBC驅動程序 |
將PostgreSQL JDBC4驅動程序jar放在tomcat web伺服器的lib目錄中。
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 INTO authors(id, name) VALUES(1, 'Rob Bal'); INSERT INTO authors(id, name) VALUES(2, 'John Carter'); INSERT INTO authors(id, name) VALUES(3, 'Chris London'); INSERT INTO authors(id, name) VALUES(4, 'Truman De Bal'); INSERT INTO authors(id, name) VALUES(5, 'Emile Capote'); INSERT INTO authors(id, name) VALUES(7, 'Breech Jabber'); INSERT INTO authors(id, name) VALUES(8, 'Bob Carter'); INSERT INTO authors(id, name) VALUES(9, 'Nelson Mand'); INSERT INTO authors(id, name) VALUES(10, 'Tennant Mark'); alter user user1 with password 'user1'; grant all on authors to user1;
Example Application
讓我們創建一個測試JSF應用程式來測試JDBC集成。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → main folder. |
3 | Create css folder under src → main → resources folder. |
4 | Create styles.css file under src → main → resources → css folder. |
5 | Modify styles.css file as explained below. |
6 | Modify pom.xml as explained below. |
7 | Create Author.java under package com.tutorialspoint.test as explained below. |
8 | Create UserData.java under package com.tutorialspoint.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | 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
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.test</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url > <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/helloworld/resources </outputDirectory> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
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 java.io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; 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; public List<Author> getAuthors() { ResultSet rs = null; PreparedStatement pst = null; Connection con = getConnection(); String stm = "Select * from authors"; List<Author> records = new ArrayList<Author>(); 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
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> <h:outputStylesheet library = "css" name = "styles.css" /> </h:head> <h:body> <h2>JDBC Integration Example</h2> <h:dataTable value = "#{userData.authors}" var = "c" styleClass = "authorTable" headerClass = "authorTableHeader" rowClasses = "authorTableOddRow,authorTableEvenRow"> <h:column><f:facet name = "header">Author ID</f:facet> #{c.id} </h:column> <h:column><f:facet name = "header">Name</f:facet> #{c.name} </h:column> </h:dataTable> </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Spring Integration
Spring提供了特殊的類delegatingvariablesolver,以無縫的方式將JSF和Spring集成在一起。
在JSF中集成Spring依賴注入(IOC)特性需要以下步驟。
Step 1: Add DelegatingVariableResolver
在faces-config.xml中添加一個變量解析器條目,以指向spring類delegatingvariablesolver。
<faces-config> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> ... </faces-config>
Step 2: Add Context Listeners
在web.xml中添加spring framework提供的ContextLoaderListener和RequestContextListener。
<web-app> ... <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> ... </web-app>
Step 3: Define Dependency
在applicationContext.xml中定義bean,該bean將用作託管bean中的依賴項。
<beans> <bean id = "messageService" class = "com.tutorialspoint.test.MessageServiceImpl"> <property name = "message" value = "Hello World!" /> </bean> </beans>
Step 4: Add Dependency
delegatingvariablesolver首先將值查找委託給JSF的默認解析器,然後委託給Spring的WebApplicationContext。這使得我們可以很容易地將基於spring的依賴注入到JSF管理的bean中。
我們在這裡將messageService作爲基於spring的依賴項注入。
<faces-config> ... <managed-bean> <managed-bean-name>userData</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>messageService</property-name> <value>#{messageService}</value> </managed-property> </managed-bean> </faces-config>
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
讓我們創建一個測試JSF應用程式來測試spring集成。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Modify pom.xml as explained below. |
3 | Create faces-config.xml in WEB-INF folder as explained below. |
4 | Modify web.xml as explained below. |
5 | Create applicationContext.xml in WEB-INF folder as explained below. |
6 | Create MessageService.java under package com.tutorialspoint.test as explained below. |
7 | Create MessageServiceImpl.java under package com.tutorialspoint.test as explained below. |
8 | Create UserData.java under package com.tutorialspoint.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | Launch your web application using appropriate URL as explained below in the last step. |
pom.xml
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.test</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.1.2.RELEASE</version> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/helloworld/resources </outputDirectory> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
faces-config.xml
<?xml version = "1.0" encoding = "UTF-8"?> <faces-config xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version = "2.0"> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> </application> <managed-bean> <managed-bean-name>userData</managed-bean-name> <managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>messageService</property-name> <value>#{messageService}</value> </managed-property> </managed-bean> </faces-config>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> </web-app>
applicationContext.xml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id = "messageService" class = "com.tutorialspoint.test.MessageServiceImpl"> <property name = "message" value = "Hello World!" /> </bean> </beans>
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; } public void setMessageService(MessageService messageService) { this.messageService = messageService; } public String getGreetingMessage() { return messageService.getGreetingMessage(); } }
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> </h:head> <h:body> <h2>Spring Integration Example</h2> #{userData.greetingMessage} </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Expression Language
JSF提供了豐富的表達式語言。我們可以使用{operation expression}符號來編寫正常操作。以下是JSF表達式語言的一些優點。
可以引用be an屬性,其中bean可以是存儲在請求、會話或應用程式範圍中的對象,也可以是託管bean。
提供對集合元素(可以是列表、映射或數組)的輕鬆訪問。
提供對預定義對象(如請求)的輕鬆訪問。
算術、邏輯和關係操作可以使用表達式語言完成。
自動類型轉換。
將缺少的值顯示爲空字符串,而不是NullPointerException。
Example Application
讓我們創建一個測試JSF應用程式來測試表達式語言。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Modify UserData.java under package com.tutorialspoint.test as explained below. |
3 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
4 | Compile and run the application to make sure the business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | 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.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
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> </h:head> <h:body> <h2>Expression Language Example</h2> Creation time: <h:outputText value = "#{userData.createTime}"/> <br/><br/> Message: <h:outputText value = "#{userData.message}"/> </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
JSF - Internationalization
國際化是一種狀態消息、GUI組件標籤、貨幣、日期不在程序中硬編碼的技術。相反,它們存儲在原始碼之外的資源包中並動態檢索。JSF提供了一種非常方便的方法來處理資源包。
要使JSF應用程式內部化,需要執行以下步驟。
Step 1: Define properties files
爲每個區域設置創建屬性文件。名稱應爲<文件名>語言環境>.properties格式。
文件名中可以省略默認區域設置。
messages.properties
greeting = Hello World!
messages_fr.properties
greeting = Bonjour tout le monde!
Step 2: Update faces-config.xml
faces-config.xml
<application> <locale-config> <default-locale>en</default-locale> <supported-locale>fr</supported-locale> </locale-config> <resource-bundle> <base-name>com.tutorialspoint.messages</base-name> <var>msg</var> </resource-bundle> </application>
Step 3: Use resource-bundle var
home.xhtml
<h:outputText value = "#{msg['greeting']}" />
Example Application
讓我們創建一個測試JSF應用程式來測試JSF中的國際化。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.tutorialspoint.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → mai folder. |
3 | Create com folder under src → main → resources folder. |
4 | Create tutorialspoint folder under src → main → resources → com folder. |
5 | Create messages.properties file under src → main → resources → com → tutorialspoint folder. Modify it as explained below. |
6 | Create messages_fr.properties file under src → main → resources → com → tutorialspoint folder. Modify it as explained below. |
7 | Create faces-config.xml in WEB-INFf older as explained below. |
8 | Create UserData.java under package com.tutorialspoint.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | 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!
faces-config.xml
<?xml version = "1.0" encoding = "UTF-8"?> <faces-config xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version = "2.0"> <application> <locale-config> <default-locale>en</default-locale> <supported-locale>fr</supported-locale> </locale-config> <resource-bundle> <base-name>com.tutorialspoint.messages</base-name> <var>msg</var> </resource-bundle> </application> </faces-config>
UserData.java
package com.tutorialspoint.test; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import 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<String,Object> countries; static { countries = new LinkedHashMap<String,Object>(); countries.put("English", Locale.ENGLISH); countries.put("French", Locale.FRENCH); } public Map<String, Object> getCountries() { return countries; } public String getLocale() { return locale; } 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<String, Object> entry : countries.entrySet()) { if(entry.getValue().toString().equals(newLocaleValue)) { FacesContext.getCurrentInstance() .getViewRoot().setLocale((Locale)entry.getValue()); } } } }
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>Internalization Language Example</h2> <h:form> <h3><h:outputText value = "#{msg['greeting']}" /></h3> <h:panelGrid columns = "2"> Language : <h:selectOneMenu value = "#{userData.locale}" onchange = "submit()" valueChangeListener = "#{userData.localeChanged}"> <f:selectItems value = "#{userData.countries}" /> </h:selectOneMenu> </h:panelGrid> </h:form> </h:body> </html>
完成所有更改後,讓我們像在JSF-First應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。
從下拉列表中更改語言。您將看到以下輸出。