codecamp

JSF 属性示例

JSF教程 - JSF属性示例


我们可以使用h:attribute标签将属性值传递给组件,或者通过动作侦听器将参数传递给组件。

以下代码显示如何使用h:attribute标签。

<h:commandButton id="submit" 
actionListener="#{userData.attributeListener}" action="result"> 
   <f:attribute name="value" value="Show Message" />        
   <f:attribute name="username" value="JSF 2.0 User" />
</h:commandButton>

标签属性

属性描述
name要设置的属性的名称
value属性的值

例子

下面的代码来自UserBean.java。

package cn.w3cschool.common;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{
  public String nickname;
  
  public void attrListener(ActionEvent event){
    nickname = (String)event.getComponent().getAttributes().get("username");
  }
  public String outcome(){
    return "result";
  }
  public String getNickname() {
    return nickname;
  }
  public void setNickname(String nickname) {
    this.nickname = nickname;
  }
  
}

以下代码来自demo.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://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
    <h:form id="form">
      <h:commandButton action="#{user.outcome}"
          actionListener="#{user.attrListener}">
        <f:attribute name="username" value="www.w3cschool.cn" />
        <f:attribute name="value" value="Click Me" />
      </h:commandButton>
    </h:form>
    </h:body>
</html>

以下代码来自result.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://java.sun.com/jsf/html">
     
    <h:body>
    #{user.nickname}
    </h:body>
</html>
下载 Attribute.zip

运行

将生成的WAR文件从目标文件夹复制到Tomcat部署文件夹,并运行Tomcat-Install-folder/bin/startup.bat。

Tomcat完成启动后,在浏览器地址栏中键入以下URL。

http://localhost:8080/simple-webapp/demo.xhtml
JSF 参数示例
JSF setPropertyActionListener示例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }