JSF入門教程

來源:互聯網
上載者:User

1. 什麼是 Java Server Faces(jsf)?

   JSF為JAVA的 Web應用使用者介面的開發人員提供了標準的編程介面、豐富可擴充的UI組件庫(一個核心的JSP標記庫用來處理事件、執行驗證以及其他非UI相關的操作和一個標準的HTML 標籤庫來表示 UI組件)、事件驅動模型等一套完整的Web應用程式框架,通過 JSF ,您可以在頁面中輕鬆自如地使用 WEB 組件、捕獲使用者行為所產生的事件、執行驗證、建立頁面導航…,當使用支援JSF的開發工具來開發 JSF 應用的時候,一切將會變得異常簡單,GUI方式拖放組件、修改組件屬性、建立組件間關聯以及編寫事件接聽程式等等

   JSF 有三部分:
     一套預製的UI組件集
     一個事件驅動的編程模型
     一個允許第三方開發人員提供附加組件的組件模型

   JSF包含處理事件所需的所有代碼和組件組織,開發人員可以忽略這些細節而專註於應用邏輯。

2. 第一個JSF程式
 
   JSF只是J2EE的一個標準,是一套介面集和一些基本實現,要使用JSF需要下載jsf的實現,可以到JSF 官方網站的 下載區 下載參考實現,也可以到 apache 下載 myfaces,這裡以使用sun的參考實現為例,在下載壓縮檔並解壓縮之後,將其 lib 目錄下的 jar 檔案複製至您的Web應用程式的/WEB-INF/lib目錄下,另外您還需要 jstl.jar 與 standard.jar 檔案,這些檔案您可以在 sample 目錄下的應用中找到,建好我們的應用目錄結構:

   hellojsf
   |-- build.xml
   |-- src
   |-- WEB-INF
   |----|-- web.xml
   |----|-- faces-config.xml
   |----|-- classes
   |----|-- lib
   |----|----|--jsf-impl.jar
   |----|----|--jsf-api.jar
   |----|----|--commons-digester.jar
   |----|----|--commons-collections.jar
   |----|----|--commons-beanutils.jar
   |----|----|--commons-logging.jar
   |----|----|--standard.jar
   |----|----|--jstl.jar

   可能只有faces-config.xml,它是jsf的基本設定檔,後面就可以看到它的作用。

   //build.xml
<project name="helloapp" default="compile" basedir=".">

<!-- ================= Property Definitions ==================== -->
<property name="src.home" value="${basedir}/src" />
<property name="classes.home" value="${basedir}/WEB-INF/classes" />
<property name="lib.home" value="${basedir}/WEB-INF/lib" />

<!-- ================= "compile" Target ==================== -->
<target name="compile">
 <javac srcdir="${src.home}" destdir="${classes.home}" debug="on">
  <classpath>
   <fileset dir="${lib.home}">
    <include name="*.jar"/>
   </fileset>
  </classpath>
 </javac>
</target>

</project>

   下面我們就開始寫程式了,沒有什麼複雜邏輯,不用細說他的流程,直接寫了。

   //hello.jsp 儲存在根目錄下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
 <html>
  <head>
   <title>
   JSF in Action - Hello, world!
   </title>
  </head>
  <body>
   <h:form id="welcomeForm">
    <h:outputText id="welcomeOutput"
     value="Welcome to JavaServer Faces!"
     style="font-family: Arial, sans-serif; font-size: 24;
     color: green;"/>
    <p>
    <h:message id="errors" for="helloInput" style="color: red"/>
    </p>
    <p>
    <h:outputLabel for="helloInput">
     <h:outputText id="helloInputLabel" value="Enter number of controls to display:"/>
    </h:outputLabel>
    <h:inputText id="helloInput" value="#{helloBean.numControls}" required="true">
     <f:validateLongRange minimum="1" maximum="500"/>
    </h:inputText>
    </p>
    <p>
    <h:panelGrid id="controlPanel"
     binding="#{helloBean.controlPanel}"
     columns="20" border="1" cellspacing="0"/>
    </p>
    <h:commandButton id="redisplayCommand" type="submit" value="Redisplay" actionListener="#{helloBean.addControls}"/>
    <h:commandButton id="goodbyeCommand" type="submit" value="Goodbye" action="#{helloBean.goodbye}" immediate="true"/>
   </h:form>
  </body>
 </html>
</f:view>

   從這個頁面可以看出,jsf 就是用他自己的UI組件代替了html標籤,又加了些特有的屬性,很容易理解,值得注意的是,所有組件都要定義在<f:view></f:view>之內,熟悉jsp的可能對”#{helloBean.numControls}“感覺很熟悉,不同的是這個是以”#“開頭的,”binding“屬性的值是個jsf el 運算式,它指定了helloBean類中的controlPanel方法可以直接對此組件進行操作,h:commandButton 是按鈕組件,可以產生 action event, 他的 actionListener 屬性制定了用helloBean類中的addControls方法來處理這個action event,其他的都比較容易理解,來看下個頁面。

   //goodbye.jsp 儲存在根目錄下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
 <html>
  <head>
   <title>
   JSF in Action - Hello, world!
   </title>
  </head>
  <body>
   <h:form id="goodbyeForm">
   <p>
   <h:outputText id="welcomeOutput" value="Goodbye!"
    style="font-family: Arial, sans-serif; font-size: 24;
    font-style: bold; color: green;"/>
   </p>
   <p>
   <h:outputText id="helloBeanOutputLabel" value="Number of controls displayed:"/>
   <h:outputText id="helloBeanOutput" value="#{helloBean.numControls}"/>
   </p>
   </h:form>
  </body>
 </html>
</f:view>

   這個頁面更簡單,只是一些輸出。

   在 hello.jsp goodbye.jsp 中都通過 jsf el 運算式引用了一個 backing bean, 叫 helloBean, 他包括了我們這個應用所需的一切

   //HelloBean.java 儲存在 src 下
package org.jia.hello;

import javax.faces.application.Application;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import java.util.List;

public class HelloBean
{
 private int numControls;
 private HtmlPanelGrid controlPanel;

 public int getNumControls()
 {
  return numControls;
 }
 public void setNumControls(int numControls)
 {
  this.numControls = numControls;
 }
 public HtmlPanelGrid getControlPanel()
 {
  return controlPanel;
 }
 public void setControlPanel(HtmlPanelGrid controlPanel)
 {
  this.controlPanel = controlPanel;
 }
 public void addControls(ActionEvent actionEvent)
 {
  Application application = FacesContext.getCurrentInstance().getApplication();
  List children = controlPanel.getChildren();
  children.clear();
  for (int count = 0; count < numControls; count++)
  {
   HtmlOutputText output = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);
   output.setValue(" " + count + " ");
   output.setStyle("color: blue");
   children.add(output);
  }
 }
 public String goodbye()
 {
  return "success";
 }
}

   jsf 的 backing bean 很簡單,不需要繼承於某個特定類,只是一個包含事件處理方法的javabean
  
   這裡面最複雜的就是 addControls 方法了,它是一個 action listener 方法,因為他接收了一個唯一的參數 ActionEvent,在 hello.jsp 中:”<h:commandButton id="redisplayCommand" type="submit" value="Redisplay" actionListener="#{helloBean.addControls}"/>“,這句話告訴 jsf,當使用者點擊"Redisplay"按鈕時jsf會用這個方法來處理 action event

   goodbye方法象 addControls 一樣,是 event listener 的一種類型,但他是於 jsf 的導航系統聯絡起來的,所以他的工作就是返回一個字串或邏輯輸出,這樣導航系統就可以決定下一個要載入的頁面,這一類的方法叫做 action methods. 在 hello.jsp 中:”<h:commandButton id="goodbyeCommand" type="submit" value="Goodbye" action="#{helloBean.goodbye}" immediate="true"/>“,當使用者點擊”Goodbye“按鈕時,goodbye方法會被執行,他只是返回"success",在設定檔中這個輸出與某個頁面相聯絡,下面就來看看設定檔faces-config.xml

   //faces-config.xml

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
 <managed-bean>
  <description>The one and only HelloBean.</description>
  <managed-bean-name>helloBean</managed-bean-name>
  <managed-bean-class>org.jia.hello.HelloBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>
 <navigation-rule>
  <description>Navigation from the hello page.</description>
  <from-view-id>/hello.jsp</from-view-id>
  <navigation-case>
   <from-outcome>success</from-outcome>
   <to-view-id>/goodbye.jsp</to-view-id>
  </navigation-case>
 </navigation-rule>
</faces-config>

   jsf 象大多數架構一樣,有一個設定檔,在之中你可以定義 導航規則、初始化javabean、註冊你自己的jsf組件、驗證器,和一些面向jsf應用其他方面的其他配置
   在這個設定檔中定義了一個bean, 指定了他的名字(這個名字就是我們在頁面中使用的名字),類全名,和使用範圍。還定義了一個導航規則,hello.jsp有一個”Goodbye“按鈕轉到其他頁,所以只有一個單獨的navigation-case,當輸出為”success"時,就會顯示goodbye.jsp。

   現在我們已經寫完了頁面,backing bean, 和設定檔,下面寫完web.xml後就可以看到效果了

   //web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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>hello world</display-name>
 <description>
  Welcome to JavaServer Faces.
 </description>
 <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>
 <welcome-file-list>
  <welcome-file>faces/hello.jsp</welcome-file>
 </welcome-file-list>
</web-app>

   FacesServlet 是做jsf 應用是一定要指定的,還設了預設頁為 hello.jsp.

   運行build, 啟動web server, 在地址欄中打入應用地址,看到剛剛寫的應用了吧,通過實際效果結合代碼,相信我們已經對jsf 已經有一個基本認識了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.