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應用程式一章中那樣編譯和運行應用程式。如果您的應用程式一切正常,這將產生以下結果。