Posted on 2008-01-07 09:39
詩特林 閱讀(2627)
評(píng)論(2) 編輯 收藏 所屬分類:
JSF
JSF1.2應(yīng)用示例代碼
本文采用JSF1.2作為一個(gè)比較初級(jí)的JSF入門應(yīng)用示例。JSF在一定程度有點(diǎn)像AWT、SWT、Swing,因此,本文示例中會(huì)使用到GUI一樣的組件。本例使用JSF開發(fā)一個(gè)簡(jiǎn)單的計(jì)算器,使用到了JSF的依賴注入、導(dǎo)航機(jī)制、轉(zhuǎn)換器、校驗(yàn)等功能。主要工作包括:
l 配置web.xml,聲明Faces Servlet及mapping;
l 配置faces-config.xml;
l 創(chuàng)建Calculator類;
l 在faces-config.xml中聲明Calculator bean;
l 創(chuàng)建index.jsp,calculator.jsp頁面;
代碼下載(已經(jīng)包含相關(guān)的lib):
http://cid-7b377ace522ff6c7.skydrive.live.com/self.aspx/JSFFirtsApp/JSFApp.rar
或:
http://vzwpuq.bay.livefilestore.com/y1ps2Mjpc3NiLKObur4qLz6dkdIsWYzNYIxiDjy-0y99NyCxo0tkyfNjuTXjIx1BBMqpFBG30iIDscfjt673NVnnViwWtZmMubo/JSFApp.rar?download
開發(fā)環(huán)境:MyEclipse6.0+Eclipse3.3+JDK5.0+Tomcat6.0+JSF1.2。整個(gè)工程的布局如下圖所示:
一.配置
首先要地web.xml中聲明Faces Servlet,表明使用JSF Servlet來處理客戶請(qǐng)求。同時(shí),并且所有使用<f:view>對(duì)JSP文件的請(qǐng)求,都應(yīng)該通過該Servlet,因此需要增加Servlet的mapping。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">
<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將會(huì)自動(dòng)的使用該文件。當(dāng)然,也可以通過web.xml中的初始化參數(shù)javax.faces.application.CONFIG_FILES來配置多個(gè)文件。因此,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>

二.創(chuàng)建代碼
1.創(chuàng)建POJO
首先需用創(chuàng)建名為Calculator的POJO(plain old java object),它通過方法綁定與屬性綁定與JSF進(jìn)行關(guān)聯(lián)。代碼如下:
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.創(chuàng)建控制器
上面的POJO是不需與JSF發(fā)生關(guān)系的,而真正需要與JSF發(fā)生的關(guān)系的類在控制器里。通過控制器實(shí)現(xiàn)界面與后面的關(guān)系。控制器類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(null, new 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(null, new 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(null, new 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(null, new 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;
}

}

三.頁面設(shè)置
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>計(jì)算器首頁</h4>
<h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
<h:form>
<h:panelGrid columns="1">
<h:commandLink action="CALCULATOR" value="計(jì)算器"/>
<h:commandLink action="CALCULATOR_REDIRECT" value="計(jì)算器 (redirect)"/>
<h:outputLink value="pages/calculator.jsf">
<h:outputText value="計(jì)算器(outputlink)"/>
</h:outputLink>
</h:panelGrid>
</h:form>
</f:view>

</body>
</html>
3.計(jì)算器頁面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>計(jì)算器示例</h4>
<h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
<h:panelGrid columns="3" rowClasses="oddRow, evenRow"
styleClass="formGrid">

<%
-- 第一個(gè)數(shù)--%>
<h:outputLabel value="第一個(gè)數(shù)" 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"/>

<%
-- 第二個(gè)數(shù)--%>
<h:outputLabel id="snl" value="第二個(gè)數(shù)" 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.結(jié)果顯示頁面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>計(jì)算器示例: 結(jié)果</h4>
<h:messages infoClass="infoClass" errorClass="errorClass" layout="table" globalOnly="true"/>
<h4>計(jì)算結(jié)果</h4>
<h:panelGrid columns="1" rowClasses="oddRow, evenRow"
styleClass="resultGrid">
<h:outputText value="第一個(gè)數(shù) #{calculatorController.calculator.firstNumber}"/>
<h:outputText value="第二個(gè)數(shù) #{calculatorController.calculator.secondNumber}"/>
<h:outputText value="計(jì)算結(jié)果 #{calculatorController.calculator.result}"/>
</h:panelGrid>
<h:form>
<h:panelGrid columns="1" rowClasses="oddRow, evenRow">
<h:commandLink action="calculator" value="返回計(jì)算器首頁"/>
<h:commandLink action="HOME" value="返回首頁"/>
<h:commandLink action="calculatorMain" value="返回計(jì)算器首頁"/>
</h:panelGrid>
</h:form>
</f:view>

</body>
</html>
四.運(yùn)行效果
1.首頁

2.計(jì)算頁面

3.結(jié)果頁面

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