`
djob2008
  • 浏览: 127422 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

core javaserver faces 笔记1

    博客分类:
  • JSF
阅读更多

编辑推荐
本书由著名畅销书作者、JSF 1.0专家组成员David Geary主笔,是JSF编程图书中的“头号指南”。作为升级版,本书内容全面覆盖JSF 1.2,囊括了各种增强特性、强大的Ajax开发技术,以及使JSF更有价值的开源创新内容。作者David Geary和Cay Horstmann在本书中深入讲解了JSF 1.2开发的各个方面,为创建高性能应用程序提供了系统级的最佳实用方案。他们利用自身对Java平台内部知识的透彻理解,为读者提供了大量解决方案、技巧、提示和编写优秀JSF 1.2产品代码的方法。即使读者是JSF或servlet新手,本书也能提供很大的帮助。
本版新增的内容包括:JSF 1.2与Java EE 5平台的更好结合;增强的JSF API;使用Shale控制Web流;使用Facelets将JSP替换为XHTML标签。此外,本版还涵盖了通过JSF进行Ajax开发的主题——从实时验证、DWR,到在JSF组件中包装Ajax和使用流行的Ajax4j sf框架。
  自动化低层细节,消除服务器端开发中不必要的复杂性从有效的UI设计和样式表到国际化,发现JSF最佳实践使用JSF和Tiles构建一致、可重用的用户界面利用外部服务,如数据库、LDAP目录、认证/授权,以及Web服务使用JBoss Seam大大简化数据库后端应用程序的开发实现自定义组件、转换器和验证器掌握JSF 1.2标签库和使用额外的标签库扩展JSF。

 内容简介
本书由著名畅销书作家、JSF 1.0专家组成员David Geary主笔,是JSF编程图书中的绝对“头号指南”,自第一版出版以来,一直是广大JSF学习者的首选教程。
本书全面深入地讲解了JSF 1.2编程的各个方面,包括JSF的各种增强特性、强大的Ajax开发技术,以及使JSF更具价值的开源创新内容,为创建高性能的应用程序提供系统级的最佳实用方案。两位传奇作者利用自身对Java平台的透彻理解,为读者提供了大量解决方案、技巧、提示和编写优秀JSF 1.2产品代码的方法,无论读者是JSF或者servlet方面的新手还是老手,都将大受裨益。

 作者简介
David Geary,从1994年到1997年在Sun Microsystems公司工作,曾任JSF 1.0专家组成员。目前,他担任Clarity Training Inc.公司的董事长,该公司是一家从事服务器端Java技术的培训咨询机构。David还是8本Java技术书籍的作者,其中包括最畅销的Graphic,Java 2系列、AdvancedJavaServer Pages和Google Web Toolkit Solutions。此外,David也是JSTL专家组成员、Apache Struts项目的执行委员,他还曾为Sun的Web Developer Certification Exam编写试题。作为一名演讲者,David在全球四大Java研讨会之一的No Fluff Just Stuff tour上经常作例行演讲。2005年,David和CraigMcClanahan合作的Shale Presentation,获得了JavaOne Rock Star的称号。

 

下面为本人读书笔记整理:

 目录
第1章 入门
1.1 为什么要选择JavaServer Faces
1.2 软件安装
1.3 一个简单的例子
1.3.1 组成部分
1.3.2 目录结构
1.3.3 构建说明
1.4 示例应用程序分析
1.4.1 Beans
1.4.2 JSF页面
1.4.3 导航
1.4.4 Servlet配置
1.4.5 欢迎文件
1.5 JSF开发环境
1.5.1 集成开发环境
1.5.2 可视构建器工具
1.5.3 使用Ant构建自动化
1.6 JSF框架服务
1.7 内幕
1.7.1 呈现页面
1.7.2 解码请求
1.7.3 生命周期
第2章 受管理Bean
2.1 Bean的定义
2.1.1 Bean属性
2.1.2 值表达式
2.2 消息包
2.2.1 具有可变部分的消息
2.2.2 设置应用程序的本地化
2.3 示例应用程序
2.4 支撑Bean
2.5 Bean作用域
2.5.1 会话作用域
2.5.2 应用程序作用域
2.5.3 请求作用域
2.5.4 生命周期说明
public class MyBean {
   @PostConstruct
   public void initialize() {
      // initialization code
   }
   @PreDestroy
   public void shutdown() {
      // shutdown code
   }
   // other bean methods
}
2.6 配置Bean
//(分成几个配置文件)
<web-app>
   <context-param>
      <param-name>javax.faces.CONFIG_FILES</param-name>
       <param-value>/WEB-INF/navigation.xml,/WEB-INF/beans.xml</param-value>
   </context-param>
   ...
</web-app>
//A bean is defined with a managed-bean element inside the top-level faces-config
//element. Minimally, you must specify the name, class, and scope of the bean.
   <faces-config>
      <managed-bean>
         <managed-bean-name>user</managed-bean-name>
         <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
   </faces-config>
//The scope can be request, session, application, or none. The none scope denotes an

2.6.1 设置属性值
<managed-bean>
   <managed-bean-name>user</managed-bean-name>
   <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
   <managed-property>
      <property-name>name</property-name>
      <value>me</value>
   </managed-property>
   <managed-property>
      <property-name>password</property-name>
      <value>secret</value>
   </managed-property>
</managed-bean>
//To initialize a property with null, use a null-value element. For example,
   <managed-property>
      <property-name>password</property-name>
      <null-value/>
   </managed-property>
   
2.6.2 初始化列表和映射(list & map)
//<value-class>可选的
<list-entries>
   <value-class>java.lang.Integer</value.class>
   <value>3</value>
   <value>1</value>
   <value>4</value>
   <value>1</value>
   <value>5</value>
</list-entries>

//<value>默认是字符串类型的
<map-entries>
   <key-class>java.lang.Integer</key-class>
   <map-entry>
      <key>1</key>
      <value>George Washington</value>
   </map-entry>
   <map-entry>
      <key>3</key>
      <value>Thomas Jefferson</value>
   </map-entry>
   <map-entry>
      <key>16</key>
      <value>Abraham Lincoln</value>
   </map-entry>
   <map-entry>
      <key>26</key>
      <value>Theodore Roosevelt</value>
   </map-entry>
</map-entries>

2.6.3 链接Bean定义
//The quiz contains a collection of problems, represented as the write-only
//problems property. You can configure it with the following instructions:
<managed-bean>
   <managed-bean-name>quiz</managed-bean-name>
   <managed-bean-class>com.corejsf.QuizBean</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
   <managed-property>
      <property-name>problems</property-name>
      <list-entries>
         <value-class>com.corejsf.ProblemBean</value-class>
         <value>#{problem1}</value>
         <value>#{problem2}</value>
         <value>#{problem3}</value>
         <value>#{problem4}</value>
         <value>#{problem5}</value>
      </list-entries>
   </managed-property>
</managed-bean>
//Of course, now we must define beans with names problem1 through problem5, like
//this:
   <managed-bean>
      <managed-bean-name>problem1</managed-bean-name>
      <managed-bean-class>
         com.corejsf.ProblemBean
      </managed-bean-class>
      <managed-bean-scope>none</managed-bean-scope>
         <managed-property>
            <property-name>sequence</property-name>
            <list-entries>
               <value-class>java.lang.Integer</value-class>
               <value>3</value>
               <value>1</value>
               <value>4</value>
               <value>1</value>
               <value>5</value>
            </list-entries>
         </managed-property>
		       <managed-property>
         <property-name>solution</property-name>
         <value>9</value>
      </managed-property>
</managed-bean>
2.6.4 字符串转换
2.7 值表达式的语法
2.7.1 使用方括号
2.7.2 映射和列表表达式
2.7.3 解析初始术语
2.7.4 复合表达式
2.7.5 方法表达式
第3章 导航
3.1 静态导航
//You give each button an action attribute—for example,
  <h:commandButton label="Login" action="login"/>
//The action must match an outcome in a navigation rule:
<navigation-rule>
   <from-view-id>/index.jsp</from-view-id>
   <navigation-case>
      <from-outcome>login</from-outcome>
      <to-view-id>/welcome.jsp</to-view-id>
   </navigation-case>
   <navigation-case>
      <from-outcome>signup</from-outcome>
      <to-view-id>/newuser.jsp</to-view-id>
   </navigation-case>
</navigation-rule>

3.2 动态导航
<h:commandButton label="Login" action="#{loginController.verifyUser}"/>
//Here is an example of an action method:
  String verifyUser() {
     if (...)
        return "success";
     else
        return "failure";
  }
   <p>
       <h:commandButton value="#{msgs.startOverButton}"
          action="#{quiz.startOverAction}"/>
   </p>
</h:form>
//done.jsp部分代码p103
 <h:form>
   <p>
       <h:outputText value="#{msgs.thankYou}"/>
       <h:outputFormat value="#{msgs.score}">
          <f:param value="#{quiz.score}"/>//参看Msg.properties: score=Your score is {0}.
       </h:outputFormat>
   </p>
   <p>
       <h:commandButton value="#{msgs.startOverButton}"
          action="#{quiz.startOverAction}"/>
   </p>
</h:form>

3.3 高级导航问题
3.3.1 重定向
Redirecting the page is slower than forwarding because another round trip to
the browser is involved. However, the redirection gives the browser a chance to
update its address field.
CAUTION: Without the redirect element, the navigation handler forwards
the current request to the next page, and all name/value pairs stored in the
request scope are carried over to the new page. However, with the redirect
element, the request scope data is lost.
3.3.2 通配符
You can use wildcards in the from-view-id element of a navigation rule, for
example:
/*
  <navigation-rule>
     <from-view-id>/secure/*</from-view-id>
     <navigation-case>
        ...
     </navigation-case>
  </navigation-rule>
*/
NOTE: Instead of leaving out a from-view-id element, you can also use one
of the following to specify a rule that applies to all pages:
/*
<from-view-id>/*</from-view-id>
or
<from-view-id>*</from-view-id>
*/
3.3.3 使用from-action
<navigation-case>
   <from-action>#{quiz.answerAction}</from-action>
   <from-outcome>again</from-outcome>
   <to-view-id>/again.jsp</to-view-id>
</navigation-case>
<navigation-case>
   <from-action>#{quiz.startOverAction}</from-action>
   <from-outcome>again</from-outcome>
   <to-view-id>/index.jsp</to-view-id>
</navigation-case>

NOTE: The navigation handler does not invoke the method inside the #{...}
delimiters. The method has been invoked before the navigation handler
kicks in. The navigation handler merely uses the from-action string as a key
to find a matching navigation case.
3.3.4 导航算法
第4章 标准JSP标签
4.1 JSF核心标签概述
4.2 JSF HTML标签概述
4.3 表单
<html>
   <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
       <head>
          <title>
              <h:outputText value="#{msgs.windowTitle}"/>
          </title>
       </head>
       <body>
          <h:form id="registerForm">
              <table>
                 <tr>
                    <td>
                       <h:outputText value="#{msgs.namePrompt}"/>
                    </td>
                    <td>
                       <h:inputText/>
                    </td>
                 </tr>
                 <tr>
                    <td>
                       <h:outputText value="#{msgs.passwordPrompt}"/>
                    </td>
                    <td>
                       <h:inputSecret id="password"/>
                    </td>
                </tr>
				             <tr>
                <td>
                   <h:outputText value="#{msgs.confirmPasswordPrompt}"/>
                </td>
                <td>
                   <h:inputSecret id="passwordConfirm"/>
                </td>
             </tr>
          </table>
          <h:commandButton type="button" value="Submit Form"
             onclick="checkPassword(this.form)"/>
      </h:form>
   </body>
   <script type="text/javascript">
   <!--
      function checkPassword(form) {
          var password = form["registerForm:password"].value;
          var passwordConfirm = form["registerForm:passwordConfirm"].value;
          if(password == passwordConfirm)
             form.submit();
          else
             alert("Password and password confirm fields don't match");
      }
   -->
   </script>
</f:view>
</html>

//javascript/src/java/com/corejsf/messages.properties
//Listing 4–2
    windowTitle=Accessing Form Elements with JavaScript
    namePrompt=Name:
    passwordPrompt=Password:
    confirmPasswordPrompt=Confirm Password:
	
4.4 文本字段和文本区域
h:inputText
h:inputSecret
h:inputTextarea
<h:inputText value="#{form.testString}" readonly="true"/>
<h:inputSecret value="#{form.passwd}" redisplay="true"/>
//The h:inputSecret examples illustrate the use of the redisplay attribute. If that
//the value is redisplayed when the page reloads. If redisplay is false, the value is
//discarded and is not redisplayed.
<h:inputSecret value="#{form.passwd}" redisplay="false"/>
<h:inputText value="inputText" style="color: Yellow; background: Teal;"/>
<h:inputText value="1234567" size="5"/>
<h:inputText value="1234567890" maxlength="6" size="10"/>
<h:inputTextarea rows="5"/>
<h:inputTextarea cols="5"/>
<h:inputTextarea value="123456789012345"rows="3" cols="10"/>
<h:inputTextarea value="#{form.dataInRows}"rows="2" cols="15"/>
4.4.1 隐藏字殷
4.4.2 使用文本字段和文本区域
4.4.3 显示文本和图片
h:outputText
h:outputFormat
h:graphicImage
<h:outputText value="#{form.testString}"/>
<h:outputText value="Number #{form.number}"/>
<h:outputText value="<input type='text' value='hello'/>"/>
<h:outputText escape="true" value='<input type="text" value="hello"/>'/>
<h:graphicImage value="/tjefferson.jpg"/>
<h:graphicImage value="/tjefferson.jpg"style="border: thin solid black"/>
4.5 按钮和链接
h:commandButton
h:commandLink
h:outputLink
4.5.1 使用命令按钮
<h:commandButton value="submit" type="submit"/>
<h:commandButton value="reset" type="reset"/>
<h:commandButton value="click this button..." onclick="alert('button clicked')" type="button"/>
<h:commandButton value="disabled" disabled="#{not form.buttonEnabled}"/>
<h:commandButton value="#{form.buttonText}" type="reset"/>

<h:commandLink>
   <h:outputText value="register"/>
</h:commandLink>
<h:commandLink style="font-style: italic">
   <h:outputText value="#{msgs.linkText}"/>
</h:commandLink>
<h:commandLink>
   <h:outputText value="#{msgs.linkText}"/>
   <h:graphicImage value="/registration.jpg"/>
</h:commandLink>
<h:commandLink value="welcome"
   actionListener="#{form.useLinkValue}"
   action="#{form.followLink}">
<h:commandLink>
   <h:outputText value="welcome"/>
   <f:param name="outcome" value="welcome"/>
</h:commandLink>
//p144~145
<h:outputLink value="http://java.net">
   <h:graphicImage value="java-dot-net.jpg"/>
   <h:outputText value="java.net"/>
</h:outputLink>
<h:outputLink value="#{form.welcomeURL}">
   <h:outputText value="#{form.welcomeLinkText}"/>
</h:outputLink>
<h:outputLink value="#introduction">
   <h:outputText value="Introduction"
      style="font-style: italic"/>
</h:outputLink>
<h:outputLink value="#conclusion"
      title="Go to the conclusion">
   <h:outputText value="Conclusion"/>
</h:outputLink>
<h:outputLink value="#toc"
      title="Go to the table of contents">
   <h2>Table of Contents</h2>
</h:outputLink>
4.5.2 使用命令链接
//example:
//ChangeLocaleBean.java
package djob2008;
/**
 * @author 邓惠敏
 * @time Jun 6, 20098:48:16 PM
 */
import java.util.Locale;
import javax.faces.context.FacesContext;
public class ChangeLocaleBean {
   public String germanAction() {
      FacesContext context = FacesContext.getCurrentInstance();
      context.getViewRoot().setLocale(Locale.CHINA);
      return null;
   }
   public String englishAction() {
      FacesContext context = FacesContext.getCurrentInstance();
      context.getViewRoot().setLocale(Locale.ENGLISH);
      return null;
   }
}
//User.java
package djob2008;
/**
 * @author 邓惠敏
 * @time 2009-5-26下午06:32:00
 */
public class User {
private String name;
private String description;
private String password;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}
}
//msg_zh.properties
indexWindowTitle=国际化
indexPageTitle=选择语言
namePrompt=姓名
passwordPrompt=密码
tellUsPrompt=关于你自己
submitPrompt=提交
//msg_en.properties
indexWindowTitle=county
indexPageTitle=please select your language
namePrompt=name
passwordPrompt=password
tellUsPrompt=about youself
submitPrompt=submit
//
<?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>
		<locale-config>
			<default-locale>en</default-locale>
			<supported-locale>zh</supported-locale>
		</locale-config>
	</application>
	<navigation-rule>
		<from-view-id>/index.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/welcome.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<navigation-rule>
		<from-view-id>/welcome.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/index.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<navigation-rule>
		<from-view-id>gzh.jsp</from-view-id>
		<navigation-case>
			<from-outcome>thankyou</from-outcome>
			<to-view-id>/thankYou.jspjsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<application>
		<resource-bundle>
			<base-name>msg</base-name>
			<var>msg</var>
		</resource-bundle>
	</application>
	<managed-bean>
		<managed-bean-name>user</managed-bean-name>
		<managed-bean-class>djob2008.User</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>
	<managed-bean>
   <managed-bean-name>localeChanger</managed-bean-name>
   <managed-bean-class>djob2008.ChangeLocaleBean</managed-bean-class>
   <managed-bean-scope>session</managed-bean-scope>
</managed-bean>	
</faces-config>
//gzh.jsp
<%@ page language="java" pageEncoding="GB18030"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
	<body>
		<f:view>
				<h:form>
					<table>
						<tr>
							<td>
								<h:commandLink immediate="true"
									action="#{localeChanger.germanAction}">
									<h:graphicImage value="images/logowiki.jpg" style="border: 0px" />
								</h:commandLink>
							</td>
							<td>
								<h:commandLink immediate="true"
									action="#{localeChanger.englishAction}">
									<h:graphicImage value="images/logowiki.jpg" style="border: 0px" />
								</h:commandLink>
							</td>
						</tr>
					</table>
					<p>
						<h:outputText value="#{msg.indexPageTitle}"
							style="font-style: italic; font-size: 1.3em" />
					</p>
					<table>
						<tr>
							<td>
								<h:outputText value="#{msg.namePrompt}" />
							</td>
							<td>
								<h:inputText value="#{user.name}" />
							</td>
						</tr>
						<tr>
							<td>
								<h:outputText value="#{msgs.passwordPrompt}" />
							</td>
							<td>
								<h:inputSecret value="#{user.password}" />
							</td>
						</tr>
						<tr>
							<td style="vertical-align: top">
								<h:outputText value="#{msg.tellUsPrompt}" />
							</td>
							<td>
								<h:inputTextarea value="#{user.description}"
									rows="5" cols="35"/>
							</td>
						</tr>
						<tr>
							<td>
								<h:commandButton value="#{msg.submitPrompt}" action="thankyou" />
							</td>
						</tr>
					</table>
				</h:form>
		</f:view>
	</body>
</html>
//thankYou.jsp
<%@ page language="java" pageEncoding="GB18030"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<body>
	<f:view>
	<h:outputText value="#{user.name}"/><p>
	<h:outputText value="#{user.password}"/><p>
	<pre><h:outputText value="#{user.description}"/></pre>
	</f:view>
</body>
</html>
4.6 选择标签
h:selectBooleanCheckbox
h:selectManyCheckbox
h:selectOneRadio
h:selectOneListbox
h:selectManyListbox
h:selectOneMenu
h:selectManyMenu
h:selectBooleanCheckbox <input type="checkbox">
h:selectManyCheckbox    
<table>
                           ...
                           <label>
                             <input type="checkbox"/>
                           </label>
                           ...
                        </table>
h:selectOneRadio      
  <table>
                           ...
                           <label>
                               <input type="radio"/>
                           </label>
                           ...
                        </table>
h:selectOneListbox      
<select>
                           <option value="Cheese">
                               Cheese
                           </option>
                           ...
                        </select>
h:selectManyListbox 
<select multiple>
                       <option value="Cheese">
                           Cheese
                       </option>
                       ...
                    </select>
h:selectOneMenu     
<select size="1">
                       <option value="Cheese">
                           Cheese
                       </option>
                       ...
                    </select>
h:selectManyMenu 
  <select multiple size="1">
                       <option value="Sunday">
                           Sunday
                       </option>
                       ...
                    </select>
4.6.1 复选框和单选按钮
h:selectBooleanCheckbox
h:selectManyCheckbox
<h:selectBooleanCheckbox value="#{form.contactMe}"/>
//The h:selectManyCheckbox tag looks like this:
  <h:selectManyCheckbox value="#{form.colors}">
     <f:selectItem itemValue="Red" itemLabel="Red"/>
     <f:selectItem itemValue="Blue" itemLabel="Blue"/>
     <f:selectItem itemValue="Yellow" itemLabel="Yellow"/>
     <f:selectItem itemValue="Green" itemLabel="Green"/>
     <f:selectItem itemValue="Orange" itemLabel="Orange"/>
  </h:selectManyCheckbox>
//h:selectOneRadio
  <h:selectOneRadio value="#{form.education}">
   <f:selectItem itemValue="High School" itemLabel="High School"/>
   <f:selectItem itemValue="Bachelor's" itemLabel="Bachelor's"/>
   <f:selectItem itemValue="Master's" itemLabel="Master's"/>
   <f:selectItem itemValue="Doctorate" itemLabel=Doctorate"/>
</h:selectOneRadio>
4.6.2 菜单和列表框
h:selectOneListbox
h:selectManyListbox
h:selectOneMenu
h:selectManyMenu
//the size attribute to specify the number of visible items
<h:selectOneListbox value="#{form.year}" size="5">
   <f:selectItem itemValue="1900" itemLabel="1900"/>
   <f:selectItem itemValue="1901" itemLabel="1901"/>
   ...
</h:selectOneListbox>
<h:selectManyListbox value="#{form.languages}">
   <f:selectItem itemValue="English" itemLabel="English"/>
   <f:selectItem itemValue="French" itemLabel="French"/>
   <f:selectItem itemValue="Italian" itemLabel="Italian"/>
   <f:selectItem itemValue="Spanish" itemLabel="Spanish"/>
   <f:selectItem itemValue="Russian" itemLabel="Russian"/>
</h:selectManyListbox>
<h:selectOneMenu value="#{form.day}">
   <f:selectItem itemValue="Sunday" itemLabel="Sunday"/>
   <f:selectItem itemValue="Monday" itemLabel="Monday"/>
   <f:selectItem itemValue="Tuesday" itemLabel="Tuesday"/>
   <f:selectItem itemValue="Wednesday" itemLabel="Wednesday"/>
   <f:selectItem itemValue="Thursday" itemLabel="Thursday"/>
   <f:selectItem itemValue="Friday" itemLabel="Friday"/>
   <f:selectItem itemValue="Saturday" itemLabel="Saturday"/>
</h:selectOneMenu>
4.6.3 项目
SelectItem(Object value)
Creates a SelectItem with a value. The item label is obtained by applying
toString() to the value.
SelectItem(Object value, String label)
Creates a SelectItem with a value and a label.
SelectItem(Object value, String label, String description)
Creates a SelectItem with a value, label, and description.
SelectItem(Object value, String label, String description, boolean disabled)
Creates a SelectItem with a value, label, description, and disabled state.

<h:selectOneRadio value="#{form.condiments}>
   <f:selectItems value="#{form.condimentItems}"/>
</h:selectOneRadio>
//例子:p169
//Form.java
package djob2008;

/**
 * @author 邓惠敏
 * @time Jun 7, 20098:03:43 AM
 */
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.model.SelectItem;
public class Form {
   enum Education { HIGH_SCHOOL, BACHELOR, MASTER, DOCTOR };
   private String name;
   private boolean contactMe;
   private Integer[] bestDaysToContact;
   private Integer yearOfBirth;
   private String[] colors;
   private String[] languages;
   private Education education;
// PROPERTY: name
   public String getName() {
      return name;
   }
   public void setName(String newValue) {
      name = newValue;
   }
   // PROPERTY: contactMe
   public boolean getContactMe() {
      return contactMe;
   }
   public void setContactMe(boolean newValue) {
       contactMe = newValue;
    }
    // PROPERTY: bestDaysToContact
    public Integer[] getBestDaysToContact() {
       return bestDaysToContact;
    }
    public void setBestDaysToContact(Integer[] newValue) {
       bestDaysToContact = newValue;
    }
    // PROPERTY: yearOfBirth
    public Integer getYearOfBirth() {
       return yearOfBirth;
    }
    public void setYearOfBirth(Integer newValue) {
       yearOfBirth = newValue;
    }
    // PROPERTY: colors
    public String[] getColors() {
       return colors;
    }
    public void setColors(String[] newValue) {
       colors = newValue;
    }
 // PROPERTY: languages
    public String[] getLanguages() {
       return languages;
    }
    public void setLanguages(String[] newValue) {
       languages = newValue;
    }
    // PROPERTY: education
    public Education getEducation() {
       return education;
    }
    public void setEducation(Education newValue) {
       education = newValue;
    }
    // PROPERTY: yearItems
    public Collection<SelectItem> getYearItems() {
	   return birthYears;
	}
	// PROPERTY: daysOfTheWeekItems
	public SelectItem[] getDaysOfTheWeekItems() {
	   return daysOfTheWeek;
	}
	// PROPERTY: languageItems
	public Map<String, Object> getLanguageItems() {
	   return languageItems;
	}
	// PROPERTY: colorItems
	public SelectItem[] getColorItems() {
	   return colorItems;
	}
	// PROPERTY: educationItems
	public SelectItem[] getEducationItems() {
	   return educationItems;
	}
	// PROPERTY: bestDaysConcatenated
	public String getBestDaysConcatenated() {
	   return concatenate(bestDaysToContact);
	}
	// PROPERTY: languagesConcatenated
	public String getLanguagesConcatenated() {
	   return concatenate(languages);
	}
	// PROPERTY: colorsConcatenated
	public String getColorsConcatenated() {
	   return concatenate(colors);
	}
	private static String concatenate(Object[] values) {
	   if (values == null)
	      return "";
	   StringBuilder r = new StringBuilder();
	   for (Object value : values) {
	      if (r.length()> 0)
	         r.append(',');
	      r.append(value.toString());
	   }
	   return r.toString();
	}
	private static SelectItem[] colorItems = {
	   new SelectItem("Red"),
	   new SelectItem("Blue"),
	   new SelectItem("Yellow"),
	   new SelectItem("Green"),
	   new SelectItem("Orange")
	};
	private static SelectItem[] educationItems = {
	   new SelectItem(Education.HIGH_SCHOOL, "High School"),
	   new SelectItem(Education.BACHELOR, "Bachelor's"),
	   new SelectItem(Education.MASTER, "Master's"),
	   new SelectItem(Education.DOCTOR, "Doctorate") };
	private static Map<String, Object> languageItems;
	static {
	   languageItems = new LinkedHashMap<String, Object>();
	   languageItems.put("English", "en"); // item, value
	   languageItems.put("French", "fr");
	   languageItems.put("Russian", "ru");
	   languageItems.put("Italian", "it");
	   languageItems.put("Spanish", "es");
	}
	  private static Collection<SelectItem> birthYears;
	  static {
	     birthYears = new ArrayList<SelectItem>();
	     for (int i = 1900; i < 2000; ++i) {
	        birthYears.add(new SelectItem(i));
	     }
	  }
	  private static SelectItem[] daysOfTheWeek;
	  static {
	     DateFormatSymbols symbols = new DateFormatSymbols();
	     String[] weekdays = symbols.getWeekdays();
	     daysOfTheWeek = new SelectItem[7];
	     for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
	        daysOfTheWeek[i - 1] = new SelectItem(new Integer(i), weekdays[i]);
	     }
	  }
	}

//getInfo.jsp
<html>
	<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
	<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
	<f:view>
		<head>
			<title><h:outputText value="#{msgs.indexWindowTitle}" /></title>
		</head>
		<body>
			<h:outputText value="#{msgs.indexPageTitle}" styleClass="emphasis" />
			<h:form>
				<table>
					<tr>
						<td>
							<h:outputText value="#{msgs.namePrompt}" />
						</td>
						<td>
							<h:inputText value="#{form.name}" />
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.contactMePrompt}" />
						</td>
						<td>
							<h:selectBooleanCheckbox value="#{form.contactMe}" />
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.bestDayPrompt}" />
						</td>
						<td>
							<h:selectManyMenu value="#{form.bestDaysToContact}">
								<f:selectItems value="#{form.daysOfTheWeekItems}" />
							</h:selectManyMenu>
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.yearOfBirthPrompt}" />
						</td>
						<td>
							<h:selectOneListbox size="5" value="#{form.yearOfBirth}">
								<f:selectItems value="#{form.yearItems}" />
							</h:selectOneListbox>
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.colorPrompt}" />
						</td>
						<td>
							<h:selectManyCheckbox value="#{form.colors}">
								<f:selectItems value="#{form.colorItems}" />
							</h:selectManyCheckbox>
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.languagePrompt}" />
						</td>
						<td>
							<h:selectManyListbox value="#{form.languages}">
								<f:selectItems value="#{form.languageItems}" />
							</h:selectManyListbox>
						</td>
					</tr>
					<tr>
						<td>
							<h:outputText value="#{msgs.educationPrompt}" />
						</td>
						<td>
							<h:selectOneRadio value="#{form.education}"
								layout="pageDirection">
								<f:selectItems value="#{form.educationItems}" />
							</h:selectOneRadio>
						</td>
					</tr>
				</table>
				<h:commandButton value="#{msgs.buttonPrompt}"
					action="showInformation" />
			</h:form>
			<h:messages/>
		</body>
	</f:view>
</html>
//showInformation.jsp
<html>
	<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
	<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
	<f:view>
		<head>
			<title><h:outputText value="#{msgs.indexWindowTitle}" /></title>
		</head>
		<body>
			<h:outputFormat value="#{msgs.thankYouLabel}">
				<f:param value="#{form.name}" />
			</h:outputFormat>
			<p>
			<table>
				<tr>
					<td>
						<h:outputText value="#{msgs.contactMeLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.contactMe}" />
					</td>
				</tr>
				<tr>
					<td>
						<h:outputText value="#{msgs.bestDayLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.bestDaysConcatenated}" />
					</td>
				</tr>
				<tr>
					<td>
						<h:outputText value="#{msgs.yearOfBirthLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.yearOfBirth}" />
					</td>
				</tr>
				<tr>
					<td>
						<h:outputText value="#{msgs.languageLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.languagesConcatenated}" />
					</td>
				</tr>
				<tr>
					<td>
						<h:outputText value="#{msgs.colorLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.colorsConcatenated}" />
					</td>
				</tr>
				<tr>
					<td>
						<h:outputText value="#{msgs.educationLabel}" />
					</td>
					<td>
						<h:outputText value="#{form.education}" />
					</td>
				</tr>
			</table>
		</body>
	</f:view>
</html>
//msgs.properties
indexWindowTitle=Checkboxes, Radio buttons, Menus, and Listboxes
indexPageTitle=Please fill out the following information
namePrompt=Name:
contactMePrompt=Contact me
bestDayPrompt=What's the best day to contact you?
yearOfBirthPrompt=What year were you born?
buttonPrompt=Submit information
languagePrompt=Select the languages you speak:
educationPrompt=Select your highest education level:
emailAppPrompt=Select your email application:
colorPrompt=Select your favorite colors:
thankYouLabel=Thank you {0}, for your information
contactMeLabel=Contact me:
bestDayLabel=Best day to contact you:
yearOfBirthLabel=Your year of birth:
colorLabel=Colors:
languageLabel=Languages:
educationLabel=Education:
//face-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">
	<managed-bean>
		<managed-bean-name>user</managed-bean-name>
		<managed-bean-class>djob2008.User</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>localeChanger</managed-bean-name>
		<managed-bean-class>
			djob2008.ChangeLocaleBean
		</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>form</managed-bean-name>
		<managed-bean-class>djob2008.Form</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>
	<navigation-rule>
		<from-view-id>getInfo.jsp</from-view-id>
		<navigation-case>
			<from-outcome>showInformation</from-outcome>
			<to-view-id>/showInformation.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

	<application>
		<locale-config>
			<default-locale>en</default-locale>
			<supported-locale>zh</supported-locale>
		</locale-config>
	</application>
	<navigation-rule>
		<from-view-id>/index.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/welcome.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<navigation-rule>
		<from-view-id>/welcome.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/index.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<navigation-rule>
		<from-view-id>gzh.jsp</from-view-id>
		<navigation-case>
			<from-outcome>thankyou</from-outcome>
			<to-view-id>/thankYou.jspjsp</to-view-id>
		</navigation-case>
	</navigation-rule>
	<application>
		<resource-bundle>
			<base-name>msg</base-name>
			<var>msg</var>
		</resource-bundle>
		<resource-bundle>
			<base-name>msgs</base-name>
			<var>msgs</var>
		</resource-bundle>
	</application>
</faces-config>
4.7 消息
Information
Warning
Error
Fatal

NOTE: By default, h:messages shows message summaries but not details.
h:message, on the other hand, shows details but not summaries. If you use
h:messages and h:message together, as we did in the preceding example, sum-
maries will appear at the top of the page, with details next to the appropriate
input field.
4.8 面板
<h:panelGrid columns="2">
   ...
   <h:panelGroup>
       <h:inputText id="name" value="#{user.name}">
       <h:message for="name"/>
   </h:panelGroup>
   ...
</h:panelGrid>
//Grouping the text field and error message puts them in the same table cell.
 <h:form>
    <h:panelGrid columns="2" rowClasses="oddRows,evenRows">
     <h:outputText value="#{msgs.namePrompt}:" />
     <h:panelGroup>
      <h:inputText id="name" value="#{user.name}" required="true"
       label="#{msgs.namePrompt}" />
      <h:message for="name" errorClass="errors" />
     </h:panelGroup>
     <h:outputText value="#{msgs.agePrompt}:" />
     <h:inputText size="3" value="#{user.age}" label="#{msgs.agePrompt}" />
    </h:panelGrid>
    <br />
    <h:commandButton value="#{msgs.buttonPrompt}" />
   </h:form>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics