JavaEE 7教程

JSF入门实战

  JavaServer Faces(JSF)是一个服务器端的用户界面(UI)为基础的Web应用程序的Java框架。 JSF允许你实现MVC设计模式。特点如下:

  • 将组件绑定到服务器端的模型。
  • 处理模型与页面导航UI事件响应的相互作用。
  • 管理UI组件在服务器的请求状态。
  • 提供简单客户端服务器端应用程序生成的事件模型 代码。
  • 轻松创建和重用自定义UI组件。 


JSF应用程序包括:

  • 用户界面网页。
  • 服务器端模型 (通常是CDI bean)
  • web.xml。
  • 可选配置文件faces-config.xml。

Facelets

  

Facelets是视图声明语言(又名JSF视图处理器)。 你可以定义一个简单的Facelets使用XHTML页面:
<?xml version='1.0' encoding='UTF-8' ?>
<!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"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
  <title>My Facelet Page Title</title>
</h:head>
<h:body>
  Hello from Facelets
</h:body>
</html>

  Facelets提供表达式语言(EL)的整合。这允许bean和界面之间双向数据绑定:
Hello from Facelets, my name is #{name.value}!

   在这段代码中,# {名称} 指的是一个请求Name对象的值value:
@Named
@RequestScoped
public class Name {
  private String value;
  //. . .
}
@Named有助于注入。

  Facelets提供了一个强大的Layout布局模板系统(类似Tiles),一个布局模板页面看起来像:
<h:body>
 <div id="top">
  <ui:insert name="top">
   <h1>Facelets are Cool!</h1>
  </ui:insert>
 </div>
 <div id="content" class="center_content">
  <ui:insert name="content">Content</ui:insert>
 </div>
 <div id="bottom">
   <ui:insert name="bottom">
     <center>Powered by GlassFish</center>
   </ui:insert>
 </div>
</h:body>

这里用了ui:insert ,定义这里插入模板客户端页面的内容,在模板客户端页面中 ui:define标签将替代这个内容。 模板客户端页面如下:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<body>
 <ui:composition template="./template.xhtml">
   <ui:define name="content">
    <h:dataTable value="#{customerSessionBean.customerNames}" var="c">
      <h:column>#{c.value}</h:column>
    </h:dataTable>
   </ui:define>
 </ui:composition>
</body>
</html>
在这段代码中,ui:insert 的名称为"top"和"bottom"没有定义,定义了名称为content的内容,所以,这段内容被插入前面ui:insert name="content"中。

资源处理(Resource Handling)

  JSF的定义一个标准的方式处理资源,如图片,CSS,JavaScript 文件。 这些资源可以被封装在classpath中的/resources目录或者/META-INF/resources中。 资源用EL表示:
<a href="#{resource['header.jpg']}">click here</a>

header.jpg捆绑在标准的资源目录。 如果资源是捆绑在一个corp库包中:
<h:graphicImage library="corp" name="header.jpg" />


JavaScript如下使用:
<h:outputScript name="myScript.js" library="scripts" target="head"/>

myscript.js是一个JavaScript资源,封装在 标准资源目录脚本的目录中。

一个CSS样式表下面这样使用:
<h:outputStylesheet name="myCSS.css" library="css" />

复合组件(Composite Components)

  通过使用Facelets和资源处理功能,JSF定义了一个复合组件,例如显示登录表单:
<h:form>
 <h:panelGrid columns="3">
  <h:outputText value="Name:" />
  <h:inputText value="#{user.name}" id="name"/>
  <h:message for="name" style="color: red" />

  <h:outputText value="Password:" />
  <h:inputText value="#{user.password}" id="password"/>
  <h:message for="password" style="color: red" />
</h:panelGrid>
<h:commandButton actionListener="#{userService.register}" id="loginButton" action="status"
value="submit"/>
</h:form>
本代码提供一个两行三列的表格。用于输入name和password两个字段,点按提交可以进行登录。

下页