Chinaunix首页 | 论坛 | 博客
  • 博客访问: 619640
  • 博文数量: 98
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 1528
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-28 16:20
文章分类

全部博文(98)

文章存档

2011年(1)

2010年(11)

2009年(44)

2008年(42)

我的朋友

分类: Java

2009-04-07 09:48:42

JSF 1.2 开发实例-计算器(包含代码)

本文采用JSF1.2作为一个比较初级的JSF入门应用示例。JSF在一定程度有点像AWTSWTSwing,因此,本文示例中会使用到GUI一样的组件。本例使用JSF开发一个简单的计算器,使用到了JSF的依赖注入、导航机制、转换器、校验等功能。主要工作包括:

  • 配置web.xml,声明Faces Servletmapping
  • 配置faces-config.xml
  • 创建Calculator类;
  • faces-config.xml中声明Calculator bean
  • 创建index.jspcalculator.jsp页面;

代码下载(已经包含相关的lib):

或:




    开发环境:
MyEclipse6.0+Eclipse3.3+JDK5.0+Tomcat6.0+JSF1.2整个工程的布局如下图所示:


一.配置

首先要地web.xml中声明Faces Servlet,表明使用JSF Servlet来处理客户请求。同时,并且所有使用JSP文件的请求,都应该通过该Servlet,因此需要增加ServletmappingWeb.xml文件的代码如下所示:
xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="/web-app_2_5.xsd" xsi:schemaLocation=" " id="WebApp_ID" version="2.5">
  
<display-name>calculator2display-name>
  
<welcome-file-list>
   
<welcome-file>index.htmlwelcome-file>
   
<welcome-file>index.htmwelcome-file>
   
<welcome-file>index.jspwelcome-file>
   
<welcome-file>default.htmlwelcome-file>
   
<welcome-file>default.htmwelcome-file>
   
<welcome-file>default.jspwelcome-file>
  
welcome-file-list>
  
<servlet>
   
<servlet-name>Faces Servletservlet-name>
   
<servlet-class>javax.faces.webapp.FacesServletservlet-class>
   
<load-on-startup>1load-on-startup>
  
servlet>
  
<servlet-mapping>
   
<servlet-name>Faces Servletservlet-name>
   
<url-pattern>/faces/*url-pattern>
   
<url-pattern>*.jsfurl-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=""
    xmlns:xsi
=""
    xsi:schemaLocation
="
   
"
    version
="1.2">

   
<application>
        
<message-bundle>messagesmessage-bundle>
   
application>

   
<managed-bean>
        
<managed-bean-name>calculatorControllermanaged-bean-name>
        
<managed-bean-class>
            com.sterning.jsfquickstart.controller.CalculatorController
        
managed-bean-class>
        
<managed-bean-scope>requestmanaged-bean-scope>
        
<managed-property>
            
<property-name>calculatorproperty-name>
            
<value>#{calculator}value>
        
managed-property>
   
managed-bean>
   
<managed-bean>
        
<managed-bean-name>calculatormanaged-bean-name>
        
<managed-bean-class>
            com.sterning.jsfquickstart.model.Calculator
        
managed-bean-class>
        
<managed-bean-scope>nonemanaged-bean-scope>
   
managed-bean>
   
   
<navigation-rule>
        
<display-name>Calculator Viewdisplay-name>
        
<from-view-id>/pages/calculator.jspfrom-view-id>
        
<navigation-case>
            
<from-outcome>resultsfrom-outcome>
            
<to-view-id>/pages/results.jspto-view-id>
        
navigation-case>
   
navigation-rule>

   
<navigation-rule>
        
<display-name>Results Pagedisplay-name>
        
<from-view-id>/pages/results.jspfrom-view-id>
        
<navigation-case>
            
<from-outcome>calculatorfrom-outcome>
            
<to-view-id>/pages/calculator.jspto-view-id>
        
navigation-case>
   
navigation-rule>

   
<navigation-rule>
        
<navigation-case>
            
<from-outcome>HOMEfrom-outcome>
            
<to-view-id>/home.jspto-view-id>
            
<redirect/>            
        
navigation-case>
   
navigation-rule>

   
<navigation-rule>
        
<navigation-case>
            
<from-outcome>CALCULATORfrom-outcome>
            
<to-view-id>/pages/calculator.jspto-view-id>
        
navigation-case>
   
navigation-rule>

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

   
<navigation-rule>
        
<from-view-id>/pages/*from-view-id>
        
<navigation-case>
            
<from-outcome>calculatorMainfrom-outcome>
            
<to-view-id>/pages/calculator.jspto-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(
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
<jsp:forward page="home.jsf"/>

2.主页home.jsp
<%@ page contentType="text/html; charset=GBK"
%>
<%@ taglib uri="" prefix="h"%>
<%@ taglib uri="" prefix="f"%>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               ""
>
<html xmlns="">
<head>
        
<title>Calculator Applicationtitle>
         
<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)"/>
               
<hutputLink value="pages/calculator.jsf">
                    
<hutputText value="计算器(outputlink)"/>
               
hutputLink>
            
h:panelGrid>
        
h:form>
        
        
f:view>

body>
html>

3.计算器页面calculator.jsp
<%@ page contentType="text/html; charset=GBK"
%>
<%@ taglib uri="" prefix="h"%>
<%@ taglib uri="" prefix="f"%>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               ""
>
<html xmlns="">
<head>
        
<title>Calculator Applicationtitle>
         
<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">
               
<%-- 第一个数--%>
               
<hutputLabel 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"/>
               
               
               
<%-- 第二个数--%>
               
<hutputLabel 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="" prefix="h"%>
<%@ taglib uri="" prefix="f"%>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               ""
>
<html xmlns="">
<head>
        
<title>Calculator Applicationtitle>
         
<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">
               
<hutputText value="第一个数  #{calculatorController.calculator.firstNumber}"/>
               
<hutputText value="第二个数 #{calculatorController.calculator.secondNumber}"/>
               
<hutputText 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.结果页面
阅读(494) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~