开发者

JSF 2 redirection problem

I have following two methods in my backing bean -

public String validateUser() {
    FacesContext facesCtx = FacesContext.getCurrentInstance();

    if(userName.equals("user1") && password.equals("pass1")) {
        User user = new User();
        user.setUserName(userName);
        HttpSession session = (HttpSession) facesCtx.getExternalContext().getSession(false);
        session.setAttribute(User.SESSION_ATTRIBUTE, user);
        return "secured/home.jsf?faces-redirect=true";
    }

    if(!userName.equals(LoginBean开发者_JAVA百科.USERNAME)) {
        FacesMessage msgForUserName = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username did not match.", null);
        facesCtx.addMessage("loginForm:userName", msgForUserName);
    }

    if(!password.equals(LoginBean.PASSWORD)) {
        FacesMessage msgForPassword = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password did not match.", null);
        facesCtx.addMessage("loginForm:password", msgForPassword);
    }

    return null;
}

public String logout() {
    logger.info("Logging out .........................................");
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facesCtx.getExternalContext().getSession(false);
    session.invalidate();
    return "login.jsf?faces-redirect=true";
}

I don't know why the redirection is working in the first method (i.e. validateUser()), but it's not working in the second method (i.e. logout()). The code inside the logout method is actually executed, the session also gets invalidated,but somehow the browser stays on the same page. And, I am using PrimeFaces p:commandButton and the ajax is enabled on both of them. Any one, any idea? Thank you.


but somehow the browser stays on the same page. And, I am using PrimeFaces p:commandButton and the ajax is enabled on both of them

I wouldn't expect it to fail. I suspect that this has something to do with the invalidated session. Try it with ajax="false" on the <p:commandButton>.


Unrelated to the problem, you should try to minimize the javax.servlet imports in your JSF managed beans. They often indicate that you're doing things in the wrong place or the clumsy way. In pure JSF2, you can invalidate the session as follows:

FacesContext.getCurrentInstance().getExternalContext().invalidateSession();

You can get/set objects in the session by the session Map.

Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
// ...

Or just make it a managed bean (property).

See also:

  • How can I create a new session with a new User login on the application?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜