I have a @SessionScoped ManagedBean that I've injected into a @RequestScoped to access the user stored in the session. 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.
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 :
@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 :
@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 :
@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 :
@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 :
<!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.
<!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. 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. 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).
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. 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. ie: Request.login(username, password)
if my memory serves me right. You have to read about the subject though, you should use hash + salt when authenticating users.