JavaServer Faces (JSF) 是一种用于构建Java Web 应用程序的标准框架(是Java Community Process 规定的JSR-127标准)。它提供了一种以组件为中心的用户界面(UI)构建方法,从而简化了Java服务器端应用程序的开发。——摘自百度百科。在Eclipse/MyEclipse中可以直接为java web项目添加JSF的特性。
以MyEclipse为例,可以右键project->Project Facets中对JavaServer Faces 2.0版本打勾。
之后java web项目中即可使用JSF,并且web.xml文件会自动修改。
JSF的使用依赖两个包:jsf-api和jsf-impl,如果项目中没有这两个jar包,要下载或者使用maven导入。
在xhtml文件中使用JSF版的EL表达式,需要有对应的Java Bean,这一点与使用Spring管理的bean类似。
要使EL表达式与Java Bean相对应,可以在jsf的配置文件中配置ManagedBean,也可以使用@ManagedBean标签进行配置,使用方法类似于Spring的@Component标签。
package cn.gsein.controller;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class HelloBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name="Rose";
public String getName() {
System.out.println("name:"+name);
return name;
}
public void setName(String name) {
this.name = name;
}
}
对应的xhtml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Hello.xhtml</title>
<meta name="keywords" content="enter,your,keywords,here" />
<meta name="description" content="A short description of this page." />
<meta name="content-type" content="text/html; charset=UTF-8" />
<!--<link rel="stylesheet" type="text/css" href="styles.css">-->
</h:head>
<h:body>
<p>This is my XHTML page.</p>
<h:form id="form">
<div
style="padding: 100px 0 0 100px; font-size: 22px; font-weight: bold">
<h:commandButton value="Say Hello To" />
<h:inputText value="#{helloBean.name}" />
<br></br> Hello,#{helloBean.name}!
</div>
</h:form>
</h:body>
</html>