菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻

基于JSF Bean的导航示例

原创
05/13 14:22 更新

JSF教程 - 基于JSF Bean的导航示例

我们还可以在托管bean中定义一个方法来返回视图名称。

下面的代码定义了一个名为NavigationController的托管bean一个名为moveToPage1()的方法。moveToPage1()返回页面名称。

@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
   public String moveToPage1(){
      return "page1";
   }
}

我们在 h:commandButton 中调用moveToPage1()方法动作属性。

这里当点击Page1按钮时,JSF会解析视图名称,page1作为page1.xhtml扩展,并找到相应的视图文件page1.xhtml在当前目录中。

<h:form>
   <h3>Using Managed Bean</h3>
   <h:commandButton action="#{navigationController.moveToPage1}"
   value="Page1" />
</h:form>

例子

下面的代码来自UserBean.java。

package com.lmonkey.common;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
  
  private static final long serialVersionUID = 1L;
  public String moveToPage1(){
    return "demo";
  }
  
  public String moveToPage2(){
    return "page2";
  }  
}

以下代码来自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">
 
    <h:body>
      <h2>This is page1.xhtml</h2>
 
    <h:form>
        <h:commandButton action="page2" value="Move to page2.xhtml" />
      <h:commandButton action="#{user.moveToPage2}" 
        value="Move to page2.xhtml by managed bean" />
    </h:form>
 
    </h:body>
</html>

以下代码来自page2.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>
      <h2>This is page2.xhtml</h2>
 
     <h:form>
           <h:commandButton action="demo" value="Move to demo.xhtml" />
        <h:commandButton action="#{user.moveToPage1}" 
          value="Move to demo.xhtml by managed bean" />
     </h:form>
 
    </h:body>
</html>

运行

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

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

http://localhost:8080/simple-webapp/demo.xhtml
综合评分:9.9 评分 请对本文进行纠错,及学习过程中有困难疑惑可在此进行讨论