简体   繁体   English

JSF在请求范围的Bean中注入和访问会话范围的ManagedBean

[英]JSF injecting and accessing Session Scoped ManagedBean in a Request Scoped Bean

I have a @SessionScoped ManagedBean that I've injected into a @RequestScoped to access the user stored in the session. 我有一个@SessionScoped ManagedBean,我已将其注入@RequestScoped中以访问存储在会话中的用户。 My code is working I just want to know if I'm using a good practice, if not can you tell me what's wrong please? 我的代码正在运行,我只想知道我是否正在使用一种良好的做法,如果不能,请告诉我出什么问题了吗? Because I'm new to JSF and I don't want to learn some bad coding from the beginning, thank you very much in advance. 因为我是JSF的新手,并且我不想从一开始就学习一些糟糕的编码,所以在此先非常感谢。

My Entity Utilisateur : 我的实体使用者:

    @Entity
    public class Utilisateur {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long      id;
    @NotNull( message = "Veuillez saisir une adresse email" )
    @Pattern( regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Merci de saisir une adresse mail valide" )
    private String    email;
    @Column( name = "mot_de_passe" )
    @NotNull( message = "Veuillez saisir un mot de passe" )
    @Pattern(regexp = ".*(?=.{8,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*", message = "Le mot de passe saisi n'est pas assez sécurisé")
    private String motDePasse;
    @NotNull( message = "Veuillez saisir un nom d'utilisateur" )
    @Size( min = 3, message = "Le nom d'utilisateur doit contenir au moins 3 caractères" )
    private String    nom;
    @Column( name = "date_inscription" )
    private Timestamp dateInscription;
//getters .. setters..
    }

My Entity Ferme : 我的实体Ferme:

@Entity
public class Ferme {

    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    @Column( name = "id_ferme" )
    private Long      id_ferme;
    @Column( name = "nom_ferme" )
    private String nom_ferme;
    @ManyToOne
    @JoinColumn( name = "utilisateur_id" )
    private Utilisateur utilisateur;

//getters .. setters..

}

My @Statless DAO : 我的@Statless DAO:

@Stateless
public class UtilisateurDao {
 @PersistenceContext( unitName = "myBD_PU" )
    private EntityManager       em;

 public List<Ferme> lister( Utilisateur user) throws DAOException {
        try {
            TypedQuery<Ferme> query = em.createQuery( "SELECT u FROM Ferme u WHERE u.utilisateur = :userid", Ferme.class );
            query.setParameter("userid", user);

            return query.getResultList();
        } catch ( Exception e ) {
            throw new DAOException( e );
        }
    }
}

My LoginBean : 我的LoginBean:

    @ManagedBean
    @SessionScoped
    public class LoginBean implements Serializable {

        private static final long serialVersionUID = 1L;

        private String email,mdp;
        private Utilisateur user;
        private boolean LoggedIn;
        @EJB 
        UtilisateurDao utilisateurDao; 

        // getters .. setters



public String authentification() {

    if (utilisateurDao.login(email, mdp) != null) {
        user = utilisateurDao.login(email, mdp);
        LoggedIn = true;
        return "listeFermes.xhtml?faces-redirect=true";
    }
    LoggedIn = false;
    FacesMessage message = new FacesMessage( "E-mail ou Mot de passe incorrecte!" );
    FacesContext.getCurrentInstance().addMessage( null, message );

    return "";
}

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "/login.xhtml?faces-redirect=true";
}
     }

My ListeFermesBean : 我的ListeFermesBean:

    @ManagedBean
    @RequestScoped
    public class ListeFermesBean implements Serializable{

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @ManagedProperty(value="#{loginBean}")
        private LoginBean loginBean;

        @EJB
        UtilisateurDao utilisateurDao;

        private Utilisateur user;
        private List<Ferme> liste;

public List<Ferme> getListe() {
        liste = new ArrayList<Ferme>();
        user = loginBean.getUser();
        return  liste = utilisateurDao.lister(user);
    }
    }

Login.xhtml : Login.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> 
    ...
    ...
      <h:form id="Login">
         <fieldset>
            <legend>Login</legend>
            <h:outputLabel for="email">Adresse email <span class="requis">*</span></h:outputLabel>
            <h:inputText id="email" value="#{loginBean.email}" size="20" maxlength="60">
            </h:inputText>
            <h:message id="emailMessage" for="email" errorClass="erreur" />
            <br />

            <h:outputLabel for="motdepasse">Mot de passe <span class="requis">*</span></h:outputLabel>
            <h:inputSecret id="motdepasse" value="#{loginBean.mdp}" size="20" maxlength="20">
            </h:inputSecret>
            <h:message id="motDePasseMessage" for="motdepasse" errorClass="erreur" />
            <br />

            <h:messages globalOnly="true" infoClass="erreur" />

            <h:commandButton value="Login" action="#{loginBean.authentification}" styleClass="sansLabel">
            </h:commandButton>
            <br />
            <h:commandButton value="Logout" action="#{loginBean.logout}" styleClass="sansLabel" />
            <br />
            <h:link value="Inscrivez-vous" outcome="inscription" />



          </fieldset>
        </h:form>   
    </h:body>
</html>

And finally the listeFermes.xhtml page which displays the List from listeFermesBean by User id stored in the object User in the session. 最后的listeFermes.xhtml页面显示从列表listeFermesBean按用户ID存储在对象User的会话。

<!DOCTYPE html>
<html lang="fr"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jstl/core">
    <h:head>
        <title>SUCCES</title>
    </h:head>
    <h:body>

        <ui:fragment rendered= "#{!loginBean.loggedIn}">
        Not logged !
        </ui:fragment>
        <ui:fragment rendered= "#{loginBean.loggedIn}">
        Welcome : #{loginBean.user.nom} <br />
        E-mail : #{loginBean.user.email} <br />

        <table border="1">
        <tr>
            <td>Nom Ferme</td>
            <td>Nom User</td>
            <td>ID User</td>
        </tr>
        <c:forEach items="#{ listeFermesBean.liste }" var="x">
        <tr>
            <td>#{x.nom_ferme}</td>
            <td>#{x.utilisateur.nom}</td>
            <td>#{x.utilisateur.id}</td>
        </tr>
        </c:forEach>      
        </table>
        </ui:fragment>

    </h:body>
</html>

As said in the comment you should use cdi injection. 如评论中所述,您应该使用cdi注入。 I believe this is a big no no as well: 我相信这也不是一件大事:

public List<Ferme> getListe() {
        liste = new ArrayList<Ferme>();
        user = loginBean.getUser();
        return  liste = utilisateurDao.lister(user);
    }

You should not do any business intensive things in your getters/setters. 应该做任何业务密集的东西在你的getter / setter方法。 The reason is those can be called multiple times in the background. 原因是那些可以在后台多次调用。

Instead you should call your services in a method that is called AFTER the service has been injected. 相反,您应该在注入服务之后使用称为“服务”的方法来调用服务。

@PostConstruct
public void init(){
    listeFerm = utilisateurDao.lister(user);
}
public List<Ferm> getListFerm(){
   return listFerm;
}

You didn't post your auth method(probably on purpose though). 您没有发布auth方法(不过可能是故意的)。

Reguarding your Auth system you said you will deal with this after but still you don't need to go through the DAO with that. 为了保护您的Auth系统,您说过以后会处理这个问题,但是仍然不需要通过DAO。 You should read about JAAS in the doc which is how to deal with this automatically then you don't need to go through a service and you can authenticate users in the bean. 您应该在文档中了解有关JAAS的知识,这是如何自动处理此问题的方法,因此您无需通过服务即可在Bean中对用户进行身份验证。 ie: Request.login(username, password) if my memory serves me right. 即: Request.login(username, password)如果我的记忆正确。 You have to read about the subject though, you should use hash + salt when authenticating users. 但是,您必须阅读有关该主题的信息,在对用户进行身份验证时应使用哈希+盐。

@Named
@SessionScoped
public class LoginBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private String email,mdp;
    private Utilisateur user;
    private boolean LoggedIn;
    private List<Ferme> liste;
    private Ferme ferme = new Ferme();
    @Inject
    UtilisateurDao utilisateurDao; 



    public Ferme getFerme() {
        return ferme;
    }
    public void setFerme(Ferme ferme) {
        this.ferme = ferme;
    }
    public void setListe(List<Ferme> liste) {
        this.liste = liste;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getMdp() {
        return mdp;
    }
    public void setMdp(String mdp) {
        this.mdp = mdp;
    }
    public Utilisateur getUser() {
        return user;
    }
    public void setUser(Utilisateur user) {
        this.user = user;
    }
    public boolean isLoggedIn() {
        return LoggedIn;
    }
    public void setLoggedIn(boolean loggedIn) {
        LoggedIn = loggedIn;
    }


    public String authentification() {

        if (utilisateurDao.login(email, mdp) != null) {
            user = utilisateurDao.login(email, mdp);
            LoggedIn = true;
            return "listeFermes.xhtml?faces-redirect=true";
        }
        LoggedIn = false;
        FacesMessage message = new FacesMessage( "Wrong E-mail or Password!" );
        FacesContext.getCurrentInstance().addMessage( null, message );

        return "";
    }



public String logout() {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("You are disconnected!"));
            ExternalContext externalContext = context.getExternalContext();
            externalContext.getFlash().setKeepMessages(true);
            externalContext.invalidateSession();

            return "/login.xhtml?faces-redirect=true";
        }

    public void deleteFerme(int id) {
            utilisateurDao.supprimerFerme(user, id);
        }

        public void addFerme() {
            utilisateurDao.creerFerme(ferme, user);
        }

        public List<Ferme> getListe() {
        return liste;
    }

    @PostConstruct
    public void init(){
        liste = utilisateurDao.lister(user);
    }

// Should I declare my Ferme and then initilize it new Ferme(); //我应该声明我的Ferme ,然后将其初始化为new Ferme(); in the @PostConstruct too ? 在@PostConstruct中吗? or leave it like it is ? 还是留下它原样? // & should I use the CRUD methods that use my "User" object stored in the session, in the @SessionScope bean? //&我应该使用@SessionScope bean中使用存储在会话中的“ User”对象的CRUD方法吗? and then call the methods in my @RequestScoped bean? 然后在我的@RequestScoped bean中调用方法? like this : 像这样 :

@SessionScope
public class LoginBean {

    ..
    ..
    public void addFerme() {
    utilisateurDao.creerFerme(ferme, user);
}
    }


    //////..... and then in the RequestScoped bean :

@RequestScoped
    ..
    ..
    @Inject
    private LoginBean loginBean;

    public void addFerme() {

            loginBean.addFerme();
        }

// login Method //登录方法

@Stateless
public class UtilisateurDao {

@PersistenceContext( unitName = "MyBD_PU" )
    private EntityManager       em;

public Utilisateur login(String email, String mdp) throws DAOException {
        Utilisateur user = null;
        Query requete = em.createQuery( JPQL_LOGIN );
        requete.setParameter( PARAM_EMAIL, email ).setParameter(PARAM_PWD, mdp);

        try {
            user = (Utilisateur) requete.getSingleResult();
            if (user!=null) {
                return user;
            }
            return null;
        } catch ( NoResultException e ) {
            return null;
        } catch ( Exception e ) {
             FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, e.getMessage(), null );
             FacesContext facesContext = FacesContext.getCurrentInstance();
             facesContext.addMessage( null, message );
        }
        return user;

    }

}

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

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