標籤:des style blog http os java io strong for
一 什麼是JSF:
JSF是JCP開發的一種Java標準,用於構建web應用程式新標準的Java架構,他提供了一種以組件為中心來開發Java web使用者介面的方法,從而簡化了開發。
二 JSF體繫結構:
JSF的主要優勢就是它是嚴格遵循“ 模型 - 視圖 - 控制器 ” 即MVC設計模式的架構, 使用者介面代碼(視圖)與應用程式資料和邏輯(模型)的清晰分離使JSF應用程式更易於管理。所有與應用程式互動的訪問都交由FacesServlet(控制器)來處理。
三 JSF小例子:
1. 代碼結構及Jar包:
2. 配置web.xml檔案:
<?xml version="1.0" encoding="ISO-8859-1"?><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"><description>JSF Demo</description><display-name>JSF Demo</display-name><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></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>
FacesServlet是整個應用的前端控制器, 所有的請求都通過FacesServlet來處理。
上面的配置中,我們將所有的.faces的請求交由FaceServlet來處理,FaceServlet會找到對應的jsp頁面
例如:如果請求是/index.faces的話,它會幫我們找到/index.jsp頁面
3. 建立受管Bean :充當控制器的角色
public class User {private String username;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}}
4. 配置faces-config.xml檔案,該檔案放置在WEB-INF下配置受管理的後台Bean:
<?xml version="1.0"?><!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN""http://java.sun.com/dtd/web-facesconfig_1_0.dtd"><faces-config><navigation-rule><from-view-id>/index.jsp</from-view-id><navigation-case><from-outcome>login</from-outcome><to-view-id>/hello.jsp</to-view-id></navigation-case></navigation-rule><managed-bean><managed-bean-name>user</managed-bean-name><managed-bean-class>com.zdp.domain.User</managed-bean-class><managed-bean-scope>session</managed-bean-scope></managed-bean></faces-config>
5. 開發基於JSF的使用者介面
(1)第一個頁面: 使用者登入 index.jsp
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%><%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@page contentType="text/html;charset=utf-8"%><html><head><title>hello, JSF</title></head><body><f:view><h:form><h3>please input your name</h3> <h:inputText value="#{user.username}" /><p><h:commandButton value="submit" action="login" /></h:form></f:view></body></html>
(2)第二個頁面: 登入成功頁面 hello.jsp
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@page contentType="text/html;charset=utf-8"%><html><head><title>welcome, JSF</title></head><body> <f:view> hi!<h:outputText value="#{user.username}"/> <h3>welcome to use JavaServer Faces!</h3> </f:view></body></html>
6. 訪問地址:http://localhost:8080/jsf/index.faces
參考文章:http://blog.csdn.net/qjyong/article/details/1833457
JSF入門之helloworld