菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

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

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

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

入驻

JSF 页面重定向示例

原创
05/13 14:22 更新

JSF教程 - JSF页面重定向示例

JSF默认在从一个页面导航到另一个页面时执行服务器页面,并且应用程序的URL不会更改。

要启用页面重定向,请在视图名称的末尾追加faces-redirect = true。

以下代码显示如何将重定向添加到JSF页面。

第1页是向前,第2页是重定向。

<h:form>
   <h3>Forward</h3>
   <h:commandButton action="page1" value="Page1" />
   <h3>Redirect</h3>
   <h:commandButton action="page2?faces-redirect=true" value="Page2" />
</h:form>

例子

以下代码来自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 start.xhtml</h2>
 
    <h:form>
        <!--<h:commandButton action="page1?faces-redirect=true" value="Page1" />-->
        <h:commandButton action="page1" value="Page1" />
      </h:form>
 
    </h:body>
</html>

以下代码来自page1.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:body>
</html>

下面的代码来自UserBean.java。

package com.lmonkey.common;

import java.io.Serializable;

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

@ManagedBean
@SessionScoped
public class UserBean implements Serializable {
  private static final long serialVersionUID = 1L;
}

运行

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

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

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