【问题标题】:Redirecting using jstl core Redirect使用 jstl core 重定向
【发布时间】:2011-09-14 12:32:32
【问题描述】:

如果我在c:if 中检查的值被评估为真,我希望用户被重定向。对于重定向,我使用c:redirect url="url"。但它不会将我重定向到页面。代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<f:view>
<c:if test="#{user.loggedIn}">
    #{user.loggedIn}
    <c:redirect url="index.xhtml"></c:redirect>
</c:if>

    Hello #{user.name}

    <h:form>
    <h:commandButton value="Logout" action="#{user.logout}" />
    </h:form>
</f:view>

这里,h代表JSF Html Taglib,c是JSTL核心标签库,f是JSF核心标签库。

【问题讨论】:

    标签: jsf redirect jstl


    【解决方案1】:

    不要在视图端控制请求/响应。在控制器端执行此操作。使用您映射到受限页面的 URL 模式的 filter,例如 /app/*。 JSF 会话范围的托管 bean 仅在过滤器中作为 HttpSession 属性提供。

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        User user = (session != null) ? (User) session.getAttribute("user") : null;
    
        if (user == null || !user.isLoggedIn()) {
            response.sendRedirect("index.xhtml"); // No logged-in user found, so redirect to index page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }
    

    失败的原因是 JSF 视图是响应的一部分,并且响应可能已经在该点提交。在调用 &lt;c:redirect&gt; 时,您应该已经在服务器日志中看到了 IllegalStateException: response already committed

    【讨论】:

    • 当我使用&lt;c:redirect&gt; 时没有抛出异常。我的问题是为什么它没有将我重定向到&lt;c:redirect&gt; 中指定的网址。 response may have been committed 是什么意思?
    • 当响应的标头已经发送到客户端(webbrowser)时,响应被提交。重定向需要未提交的响应,因为需要设置 Location 标头以指示客户端在给定位置发送新的 GET 请求(因此,重定向)。
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2012-09-23
    • 2011-08-27
    • 2020-01-09
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多