使用jstl核心重定向进行重定向 [英] Redirecting using jstl core Redirect
问题描述
如果我在c:if
中检查的值评估为true,我希望用户被重定向.对于重定向,我正在使用c:redirect url="url"
.但这并没有将我重定向到该页面.这是代码:
I want user to be redirected if the value I am checking in c:if
is evaluated to true. For redirecting, I am using c:redirect url="url"
. But it is not redirecting me to the page. Here is the code:
<!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核心taglib,f
是JSF核心taglib.
Here, h
represents JSF Html Taglib, c
is JSTL core taglib, f
is JSF core taglib.
推荐答案
不要在视图侧控制请求/响应.在控制器端执行此操作.使用过滤器,将其映射到受限页面的URL模式,例如/app/*
.在过滤器中,JSF会话范围内的受管Bean只能作为HttpSession
属性使用.
Do not control the request/response in the view side. Do it in the controller side. Use a filter which you map on URL pattern of the restricted pages, such as /app/*
. JSF session scoped managed beans are just available as HttpSession
attributes in the filter.
@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视图是响应的一部分,并且该响应可能已在此时提交.您应该已经在调用<c:redirect>
的位置在服务器日志中看到IllegalStateException: response already committed
.
The reason that this fails is that a JSF view is part of the response and that the response may already have been committed at that point. You should have seen an IllegalStateException: response already committed
in the server logs at the point <c:redirect>
is invoked.
这篇关于使用jstl核心重定向进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!