JSF1.2应用示例代码
本文采用JSF1.2作为一个比较初级的JSF入门应用示例。JSF在一定程度有点像AWT、SWT、Swing,因此,本文示例中会使用到GUI一样的组件。本例使用JSF开发一个简单的计算器,使用到了JSF的依赖注入、导航机制、转换器、校验等功能。主要工作包括:
l 配置web.xml,声明Faces Servlet及mapping;
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,因此需要增加Servlet的mapping。Web.xml文件的代码如下所示:
< 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文件的代码如下:
< 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
首先需用创建名为Calculator的POJO(plain old java object),它通过方法绑定与属性绑定与JSF进行关联。代码如下:
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的代码如下:
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;
}
}
三.页面设置
1.首页index.jsp
2.主页home.jsp
<% @ 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
<% @ 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
<% @ 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