You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Facelets页面page1导航至Servlet生成页面page2的404问题

问题

在一个Web应用中存在两个页面:page1是基于.xhtml文件的Facelet页面,page2由Servlet生成。

page1.xhtml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="jakarta.faces.html"
      xmlns:f="jakarta.faces.core"
      >
    <h:head>
        <title>TODO supply a title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </h:head>
    <h:body>
        <h:button outcome="yolo" value="move on"/>
    </h:body>
</html>

生成page2的Servlet代码:

package tests;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/abc")
public class DummySrv extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        resp.getWriter().write("abc");
    }
    
}

已在faces-config.xml中添加导航规则:

<navigation-rule>
  <from-view-id>
    /page1.xhtml
  </from-view-id>
  <navigation-case>
    <from-outcome>
      yolo
    </from-outcome>
    <to-view-id>
      /abc
    </to-view-id>
  </navigation-case>
</navigation-rule>

点击page1上的“move on”按钮时,导航规则会自动添加.xhtml后缀,导致出现404错误,请问如何实现从page1到page2的正确导航?

解决方案

方法一:给导航规则添加重定向属性

修改faces-config.xml中的导航规则,在<navigation-case>内添加<redirect/>标签,JSF发起重定向时不会自动给目标路径添加.xhtml后缀:

<navigation-rule>
  <from-view-id>/page1.xhtml</from-view-id>
  <navigation-case>
    <from-outcome>yolo</from-outcome>
    <to-view-id>/abc</to-view-id>
    <redirect/>
  </navigation-case>
</navigation-rule>

方法二:直接在h:button中指定Servlet路径

跳过JSF导航规则的后缀自动处理逻辑,直接将h:button的outcome设置为Servlet的URL路径:

<!-- 直接指定Servlet路径 -->
<h:button outcome="/abc" value="move on"/>

<!-- 若需要适配上下文路径,可使用EL表达式 -->
<h:button outcome="#{request.contextPath}/abc" value="move on"/>

方法三:全局修改JSF后缀映射

在web.xml中调整JSF的Servlet映射规则,比如改用*.faces作为JSF请求后缀,这样只有匹配该后缀的请求才会被JSF处理,跳转非JSF资源时不会自动添加.xhtml:

<servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.faces</url-pattern>
</servlet-mapping>

修改后page1的访问路径变为/page1.faces,跳转/abc时不会触发后缀自动添加逻辑。

内容的提问来源于stack exchange,提问作者zajer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:33:27