繁体   English   中英

JSF HttpSession登录传递参数?

[英]JSF HttpSession Login Passing Parameter?

我有使用Hibernate + JSF 2.0的登录表单,我的代码工作正常,但是我的问题是登录后如何显示用户个人资料,例如名字,姓氏等……我的朋友告诉我应该使用HttpSession,但我可以吗?如何使用它。 希望有人建议我最好的方法。 这是我的代码:

login.xhtml

<h:form id="formLogin">
    <h:outputLabel for="username" value="Username:" />
    <p:inputText value="#{loginBean.username.username}"
                 id="username" required="true" label="username" styleClass="span12" />

    <h:outputLabel for="password" value="Password:" />
    <h:inputSecret value="#{loginBean.username.password}"
                   id="password" required="true" label="password" styleClass="span12" />
    <p:commandButton id="loginButton" value="Login" update=":growl" ajax="false"
                     action="#{loginBean.login}"/>
</h:form>

loginBean.java

public class loginBean {

    private Users username;
    private UsersDao userdao;

    /** Creates a new instance of loginBean */
    public loginBean() {
        userdao = new UsersDao();
        username = new Users();
    }

    public Users getUsername() {
        return username;
    }

    public void setUsername(Users username) {
        this.username = username;
    }

    public String login(){
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg;
        boolean loggedIn;

        username = userdao.login(username);
        if(username != null) {
            loggedIn = true;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", username.getPassword());
            return "index";
        } else {
            loggedIn = false;
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
            if(this.username == null){
                this.username = new Users();
            }
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public String logout(){
        RequestContext context = RequestContext.getCurrentInstance();
        FacesContext facescontext = FacesContext.getCurrentInstance();

        HttpSession sesion = (HttpSession) facescontext.getExternalContext().getSession(false);
        sesion.invalidate();

        return "logout";
    }

}

您有两种选择:

  1. 保持LoginBean @SessionScoped并将其注入您需要的位置。 请记住,可以使用@ManagedProperty批注将JSF托管bean注入其他bean。 将已记录的用户信息存储到LoginBean您可以从此处检索它。 您也可以这样从任何视图中引用它:

    #{loginBean.userName}

  2. 将您的LoginBean更改为@ViewScoped并使其仅管理与登录相关的视图。 然后向其注入一个@SessionScoped bean,将其称为LoginInfo 登录执行后,创建您的LoginInfo Bean,可以从同一会话中的其余Bean进行访问。

无需使用HttpSession JSF提供了@SessionScoped托管bean,以避免必须自己在其中注入值。

也可以看看:

暂无
暂无

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

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