posts - 310, comments - 6939, trackbacks - 0, articles - 3
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          JSF1.2應用示例

          Posted on 2008-01-07 09:39 詩特林 閱讀(2631) 評論(2)  編輯  收藏 所屬分類: JSF
           

          JSF1.2應用示例代碼

           

          本文采用JSF1.2作為一個比較初級的JSF入門應用示例。JSF在一定程度有點像AWT、SWTSwing,因此,本文示例中會使用到GUI一樣的組件。本例使用JSF開發一個簡單的計算器,使用到了JSF的依賴注入、導航機制、轉換器、校驗等功能。主要工作包括:

          l         配置web.xml,聲明Faces Servletmapping;

          l         配置faces-config.xml;

          l         創建Calculator類;

          l         faces-config.xml中聲明Calculator bean;

          l         創建index.jsp,calculator.jsp頁面;

           

          代碼下載(已經包含相關的lib):

          http://cid-7b377ace522ff6c7.skydrive.live.com/self.aspx/JSFFirtsApp/JSFApp.rar

          或:

          http://vzwpuq.bay.livefilestore.com/y1ps2Mjpc3NiLKObur4qLz6dkdIsWYzNYIxiDjy-0y99NyCxo0tkyfNjuTXjIx1BBMqpFBG30iIDscfjt673NVnnViwWtZmMubo/JSFApp.rar?download

           



              開發環境:MyEclipse6.0+Eclipse3.3+JDK5.0+Tomcat6.0+JSF1.2整個工程的布局如下圖所示:


           

          一.配置

           

          首先要地web.xml中聲明Faces Servlet,表明使用JSF Servlet來處理客戶請求。同時,并且所有使用<f:view>JSP文件的請求,都應該通過該Servlet,因此需要增加ServletmappingWeb.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">
            
          <display-name>calculator2</display-name>
            
          <welcome-file-list>
              
          <welcome-file>index.html</welcome-file>
              
          <welcome-file>index.htm</welcome-file>
              
          <welcome-file>index.jsp</welcome-file>
              
          <welcome-file>default.html</welcome-file>
              
          <welcome-file>default.htm</welcome-file>
              
          <welcome-file>default.jsp</welcome-file>
            
          </welcome-file-list>
            
          <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>
              
          <url-pattern>*.jsf</url-pattern>
            
          </servlet-mapping>
          </web-app>

           

          如果在WEB-INF目錄下面放置faces-config.xml文件的話,Faces Servlet將會自動的使用該文件。當然,也可以通過web.xml中的初始化參數javax.faces.application.CONFIG_FILES來配置多個文件。因此,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_1_2.xsd"

              version
          ="1.2">

              
          <application>
                  
          <message-bundle>messages</message-bundle>
              
          </application>

              
          <managed-bean>
                  
          <managed-bean-name>calculatorController</managed-bean-name>
                  
          <managed-bean-class>
                      com.sterning.jsfquickstart.controller.CalculatorController
                  
          </managed-bean-class>
                  
          <managed-bean-scope>request</managed-bean-scope>
                  
          <managed-property>
                      
          <property-name>calculator</property-name>
                      
          <value>#{calculator}</value>
                  
          </managed-property>
              
          </managed-bean>
              
          <managed-bean>
                  
          <managed-bean-name>calculator</managed-bean-name>
                  
          <managed-bean-class>
                      com.sterning.jsfquickstart.model.Calculator
                  
          </managed-bean-class>
                  
          <managed-bean-scope>none</managed-bean-scope>
              
          </managed-bean>
              
              
          <navigation-rule>
                  
          <display-name>Calculator View</display-name>
                  
          <from-view-id>/pages/calculator.jsp</from-view-id>
                  
          <navigation-case>
                      
          <from-outcome>results</from-outcome>
                      
          <to-view-id>/pages/results.jsp</to-view-id>
                  
          </navigation-case>
              
          </navigation-rule>

              
          <navigation-rule>
                  
          <display-name>Results Page</display-name>
                  
          <from-view-id>/pages/results.jsp</from-view-id>
                  
          <navigation-case>
                      
          <from-outcome>calculator</from-outcome>
                      
          <to-view-id>/pages/calculator.jsp</to-view-id>
                  
          </navigation-case>
              
          </navigation-rule>

              
          <navigation-rule>
                  
          <navigation-case>
                      
          <from-outcome>HOME</from-outcome>
                      
          <to-view-id>/home.jsp</to-view-id>
                      
          <redirect/>            
                  
          </navigation-case>
              
          </navigation-rule>

              
          <navigation-rule>
                  
          <navigation-case>
                      
          <from-outcome>CALCULATOR</from-outcome>
                      
          <to-view-id>/pages/calculator.jsp</to-view-id>
                  
          </navigation-case>
              
          </navigation-rule>

              
          <navigation-rule>
                  
          <navigation-case>
                      
          <from-outcome>CALCULATOR_REDIRECT</from-outcome>
                      
          <to-view-id>/pages/calculator.jsp</to-view-id>
                      
          <redirect/>            
                  
          </navigation-case>
              
          </navigation-rule>

              
          <navigation-rule>
                  
          <from-view-id>/pages/*</from-view-id>
                  
          <navigation-case>
                      
          <from-outcome>calculatorMain</from-outcome>
                      
          <to-view-id>/pages/calculator.jsp</to-view-id>
                      
          <redirect/>
                  
          </navigation-case>
              
          </navigation-rule>

          </faces-config>

           

          二.創建代碼

           

          1.創建POJO

          首先需用創建名為CalculatorPOJOplain old java object),它通過方法綁定與屬性綁定與JSF進行關聯。代碼如下:

          package com.sterning.jsfquickstart.model;


          public class Calculator {
           
              
          private int firstNumber = 0;

              
          private int result = 0;

              
          private int secondNumber = 0;
              
              
          public void add() {
                  result 
          = firstNumber + secondNumber;
              }


              
          public void multiply() {
                  result 
          = firstNumber * secondNumber;
              }


              
          public void divide() {
                  
          this.result = this.firstNumber / this.secondNumber;
              }


              
          public void clear () {
                  
          this.firstNumber = 0;
                  
          this.secondNumber = 0;
                  result 
          = 0;
              }

              
              
              
          /* ---------- 屬性 ------------- */
              
              
          public int getFirstNumber() {
                  
          return firstNumber;
              }


              
          public void setFirstNumber(int firstNumber) {
                  
          this.firstNumber = firstNumber;
              }


              
          public int getResult() {
                  
          return result;
              }


              
          public void setResult(int result) {
                  
          this.result = result;
              }


              
          public int getSecondNumber() {
                  
          return secondNumber;
              }


              
          public void setSecondNumber(int secondNumber) {
                  
          this.secondNumber = secondNumber;
              }


              
          }


           

          2.創建控制器

          上面的POJO是不需與JSF發生關系的,而真正需要與JSF發生的關系的類在控制器里。通過控制器實現界面與后面的關系。控制器類CalculatorController的代碼如下:

          package com.sterning.jsfquickstart.controller;

          import javax.faces.application.FacesMessage;
          import javax.faces.component.UIInput;
          import javax.faces.context.FacesContext;

          import com.sterning.jsfquickstart.model.Calculator;

          public class CalculatorController {

              
          private Calculator calculator;    
              
          private UIInput firstNumberInput;
              
          private UIInput secondNumberInput;
                  

              
          public void setCalculator(Calculator calculator) {
                  
          this.calculator = calculator;
              }


              
          public Calculator getCalculator() {
                  
          return calculator;
              }


              
          public String add() {

                  FacesContext facesContext 
          = FacesContext.getCurrentInstance();

                  
          try {
                      calculator.add();
                      facesContext.addMessage(
          nullnew FacesMessage(
                              FacesMessage.SEVERITY_INFO, 
          "加法成功"null));

                  }
           catch (Exception ex) {
                      facesContext.addMessage(
          null
                              
          new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
                  }

                  
          return "results";
              }


              
          public String multiply() {

                  FacesContext facesContext 
          = FacesContext.getCurrentInstance();

                  
          try {
                      calculator.multiply();
                      facesContext.addMessage(
          nullnew FacesMessage(
                              FacesMessage.SEVERITY_INFO, 
          "乘法成功"null));

                  }
           catch (Exception ex) {
                      facesContext.addMessage(
          null
                              
          new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
                  }

                  
          return "results";
              }


              
          public String divide() {

                  FacesContext facesContext 
          = FacesContext.getCurrentInstance();

                  
          try {
                      calculator.divide();
                      facesContext.addMessage(
          nullnew FacesMessage(
                              FacesMessage.SEVERITY_INFO, 
          "除法成功"null));

                  }
           catch (Exception ex) {
                      
          if (ex instanceof ArithmeticException) {
                          secondNumberInput.setValue(Integer.valueOf(
          1));
                      }

                      facesContext.addMessage(
          null
                              
          new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
                  }

                  
          return "results";
              }


              
          public String clear() {

                  FacesContext facesContext 
          = FacesContext.getCurrentInstance();

                  
          try {
                      calculator.clear();
                      facesContext.addMessage(
          nullnew FacesMessage(
                              FacesMessage.SEVERITY_INFO, 
          "清空成功"null));

                  }
           catch (Exception ex) {
                      facesContext.addMessage(
          null
                              
          new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
                  }

                  
          return null;
              }


              
          public String getFirstNumberStyleClass() {
                  
          if (firstNumberInput.isValid()) {
                      
          return "labelClass";
                  }
           else {
                      
          return "errorClass";
                  }
                  
              }


              
          public String getSecondNumberStyleClass() {
                  
          if (secondNumberInput.isValid()) {
                      
          return "labelClass";
                  }
           else {
                      
          return "errorClass";
                  }
                  
              }


              
          public UIInput getFirstNumberInput() {
                  
          return firstNumberInput;
              }


              
          public void setFirstNumberInput(UIInput firstNumberInput) {
                  
          this.firstNumberInput = firstNumberInput;
              }


              
          public UIInput getSecondNumberInput() {
                  
          return secondNumberInput;
              }


              
          public void setSecondNumberInput(UIInput secondNumberInput) {
                  
          this.secondNumberInput = secondNumberInput;
              }


              
          }

           

          三.頁面設置

           

          1.首頁index.jsp

          <jsp:forward page="home.jsf"/>
           

          2.主頁home.jsp

          <%@ page contentType="text/html; charset=GBK" %>
          <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
          <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

          <!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>Calculator Application</title>
                   
          <link rel="stylesheet" 
                       type
          ="text/css" href="<%=request.getContextPath()%>/css/main.css" />
          </head>
          <body>
          <f:view>
                  
          <h4>計算器首頁</h4>
                  
          <h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
                  
          <h:form>
                      
          <h:panelGrid columns="1">
                          
          <h:commandLink action="CALCULATOR" value="計算器"/>
                          
          <h:commandLink action="CALCULATOR_REDIRECT" value="計算器 (redirect)"/>
                          
          <h:outputLink value="pages/calculator.jsf">
                              
          <h:outputText value="計算器(outputlink)"/>
                          
          </h:outputLink>
                      
          </h:panelGrid>
                  
          </h:form>
                  
                  
          </f:view>

          </body>
          </html>

           

          3.計算器頁面calculator.jsp

          <%@ page contentType="text/html; charset=GBK" %>
          <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
          <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

          <!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>Calculator Application</title>
                   
          <link rel="stylesheet" 
                       type
          ="text/css" href="<%=request.getContextPath()%>/css/main.css" />
          </head>
          <body>
          <f:view>
              
          <h:form id="calcForm">
                  
          <h4>計算器示例</h4>
                  
          <h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
                  
          <h:panelGrid columns="3" rowClasses="oddRow, evenRow" 
                              styleClass
          ="formGrid">
                          
          <%-- 第一個數--%>
                          
          <h:outputLabel value="第一個數" for="firstNumber" 
                                          styleClass
          ="#{calculatorController.firstNumberStyleClass}"/>
                          
          <h:inputText id="firstNumber" label="First Number"
                              value
          ="#{calculatorController.calculator.firstNumber}" required="true"
                              binding
          ="#{calculatorController.firstNumberInput}" />
                          
          <h:message for="firstNumber" errorClass="errorClass"/>
                          
                          
                          
          <%-- 第二個數--%>
                          
          <h:outputLabel id="snl" value="第二個數" for="secondNumber"
                                          styleClass
          ="#{calculatorController.secondNumberStyleClass}"/>
                          
          <h:inputText id="secondNumber" label="Second Number"
                              value
          ="#{calculatorController.calculator.secondNumber}" required="true"
                              binding
          ="#{calculatorController.secondNumberInput}"/>
                          
          <h:message for="secondNumber" errorClass="errorClass"/>
                  
          </h:panelGrid>
                  
          <div>
                      
          <h:commandButton action="#{calculatorController.add}"  value="加法" />
                      
          <h:commandButton action="#{calculatorController.multiply}"  value="乘法" />
                      
          <h:commandButton action="#{calculatorController.divide}"  value="除法" />
                      
          <h:commandButton action="#{calculatorController.clear}"  value="清空" immediate="true"/>
                      
          <h:commandButton action="HOME" value="首頁" immediate="true"/>
                  
          </div>
              
          </h:form>
          </f:view>

          </body>
          </html>

           

          4.結果顯示頁面results.jsp

          <%@ page contentType="text/html; charset=GBK" %>
          <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
          <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

          <!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>Calculator Application</title>
                   
          <link rel="stylesheet" 
                       type
          ="text/css" href="<%=request.getContextPath()%>/css/main.css" />
          </head>
          <body>
          <f:view>
                  
          <h4>計算器示例: 結果</h4>
                  
          <h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
                  
          <h4>計算結果</h4>
                  
          <h:panelGrid columns="1" rowClasses="oddRow, evenRow"
                          styleClass
          ="resultGrid">
                          
          <h:outputText value="第一個數  #{calculatorController.calculator.firstNumber}"/>
                          
          <h:outputText value="第二個數 #{calculatorController.calculator.secondNumber}"/>
                          
          <h:outputText value="計算結果  #{calculatorController.calculator.result}"/>
                  
          </h:panelGrid>
                  
          <h:form>
                  
          <h:panelGrid columns="1" rowClasses="oddRow, evenRow">
                      
          <h:commandLink action="calculator" value="返回計算器首頁"/>
                      
          <h:commandLink action="HOME" value="返回首頁"/>
                      
          <h:commandLink action="calculatorMain" value="返回計算器首頁"/>
                  
          </h:panelGrid>
                  
          </h:form>
                          
          </f:view>

          </body>
          </html>

           

          四.運行效果

           

          1.首頁

           

          2.計算頁面

           

          3.結果頁面


          參考:http://www.ibm.com/developerworks/edu/j-dw-java-jsf1-i.html?S_TACT=105AGX02&S_CMP=HP


          評論

          # re: JSF1.2應用示例  回復  更多評論   

          2008-01-07 12:58 by 你是樓豬
          曾經看過這個視頻

          # re: JSF1.2應用示例  回復  更多評論   

          2008-05-02 09:10 by slieer
          謝謝!不錯!QQ:491089448
          主站蜘蛛池模板: 长岭县| 和田县| 海兴县| 丹巴县| 双峰县| 伊宁市| 镇平县| 阿合奇县| 清涧县| 临武县| 大埔区| 邵武市| 那曲县| 北海市| 永兴县| 六安市| 安国市| 体育| 鄂温| 湾仔区| 耿马| 五华县| 铁岭县| 运城市| 南投市| 加查县| 确山县| 孝义市| 淮滨县| 桃园县| 安徽省| 溆浦县| 民乐县| 二连浩特市| 铜鼓县| 高安市| 南川市| 海口市| 田东县| 华容县| 比如县|