简体   繁体   English

页面加载时JSF重定向

[英]JSF redirect on page load

简短的问题:是否可以进行重定向,例如当用户未登录时,何时呈现页面?

For that you should use a Filter . 为此你应该使用Filter

Eg 例如

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { 
    if (((HttpServletRequest) request).getSession().getAttribute("user") == null) {
        ((HttpServletResponse) response).sendRedirect("error.jsf"); // Not logged in, so redirect to error page.
    } else {
        chain.doFilter(request, response); // Logged in, so just continue.
    }
}

Here I assume that the User is been placed in the session scope as you would normally expect. 在这里,我假设User已按照您通常的预期放入会话范围。 It can be a session scoped JSF managed bean with the name user . 它可以是名为user的会话作用域JSF托管bean。

A navigation rule is not applicable as there's no means of a "bean action" during a normal GET request. 导航规则不适用,因为在正常的GET请求期间没有“bean操作”的方法。 Also doing a redirect when the managed bean is about to be constructed ain't gong to work, because when a managed bean is to be constructed during a normal GET request, the response has already started to render and that's a point of no return (it would only produce IllegalStateException: response already committed ). 当要构建托管bean时,还要进行重定向是不可行的,因为当在正常的GET请求期间构造托管bean时,响应已经开始呈现并且这是一个无法返回的点(它只会产生IllegalStateException: response already committed )。 A PhaseListener is cumbersome and overwhelming as you actually don't need to listen on any of the JSF phases. PhaseListener很麻烦且非常庞大,因为您实际上不需要监听任何JSF阶段。 You just want to listen on "plain" HTTP requests and the presence of a certain object in the session scope. 您只想听取“普通”HTTP请求以及会话范围中某个对象的存在。 For that a Filter is perfect. 为此,过滤器是完美的。

Yes: 是:

if(!isLoggedIn) {
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}

您可以使用PhaseListener指定何时进行重定向。

In a PhaseListener try: PhaseListener尝试:

FacesContext ctx = FacesContext.getCurrentContext();
ctx.getApplication().getNavigationHandler()
     .handleNavigation(ctx, null, "yourOutcome");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM