托管Bean是JSF中重要的组件,JSF框架对托管Bean没太多要求,因此托管Bean是一个POJO,通常一个托管Bean与一个应用页面,托管Bean定义了与页面自检关联的属性和方法。
托管Bean成分:
- 托管Bean的属性可以绑定到对象
- 组建值
- 组件实例(本身)
- 转换器实现
- 校验器实现
- 方法可以完成以下功能
- 完成导航处理
- 处理Action事件
- 处理ValueChanged事件
- 完成组件验证值
托管Bean分类
BackBean、Controller托管Bean、模型Bean、Utily托管Bean
face-config.xml
<managed-bean>
<managed-bean-name>bookBean</managed-bean-name>
<managed-bean-class>com.test.bean.BookBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
com.test.bean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.test.bean;
import static javafx.scene.paint.Color.color;
import javax.faces.component.html.HtmlInputText;
/**
*
* @author Administrator
*/
public class BookBean {
private String bookname; // 绑定组件值
private HtmlInputText priceInputText; // 绑定组件本身
public String guess(){
if ("Java".equals(bookname)){
priceInputText.setValue(100);
priceInputText.setStyle("background-color:green");
}else{
priceInputText.setValue(0.0);
priceInputText.setStyle("background-color:red");
}
return null;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public HtmlInputText getPriceInputText() {
return priceInputText;
}
public void setPriceInputText(HtmlInputText priceInputText) {
this.priceInputText = priceInputText;
}
}
index.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>图书猜价</title>
</h:head>
<h:body>
<p>666</p>
<h:form>
图书名:<h:inputText value="#{bookBean.bookname}"/><br/>
价格:<h:inputText binding="#{bookBean.priceInputText}"/><br/>
<h:commandButton value="猜价" action="#{bookBean.guess}" />
</h:form>
</h:body>
</html>