I have create basic login page but not work that page. Why display whitelable error page? - spring

I have created a basic login page but it does not work that page display only the Whitelabel error and does not create a table in the database. (without encoding)
Not indicate the error.
I am a beginner at coding.
Who can support finding that error? and explain
LoginController
package Controller;
import domain.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import repository.LoginRepository;
import service.LoginService;
import java.util.Objects;
#Controller
public class LoginController {
#Autowired
private LoginService loginService;
#GetMapping("/login")
public ModelAndView login() {
ModelAndView mav = new ModelAndView("login");
mav.addObject("user", new login());
return mav;
}
#PostMapping("/login")
public String login(#ModelAttribute("user") login user){
login oauthUser = loginService.login(user.getUsername(), user.getPassword());
System.out.print(oauthUser);
if(Objects.nonNull(oauthUser)) {
return "redirect:/";
} else {
return "redirect:/login";
}
}
}
domain (login)
package domain;
import javax.persistence.*;
#Entity
#Table(name="login")
public class login {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
public login(){
}
public login(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
LoginRepository
package repository;
import domain.login;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface LoginRepository extends JpaRepository<login, Long>{
login findByUsernameAndPassword(String username, String password);
}
LoginService
package service;
import domain.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.LoginRepository;
#Service
public class LoginService {
#Autowired
private LoginRepository repo;
public login login(String username, String password) {
login user = repo.findByUsernameAndPassword(username, password);
return user;
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Home Page</title>
</head>
<body>
<h1>Welcome To Home Page</h1>
</body>
</html>
login.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
</head>
<body>
<h1>login page</h1>
<form th:action="#{/login}" th:object="${user}" method="post">
<div class="form-group">
<label>User Name</label>
<input type="text" th:field="*{username}">
</div>
<div class="form-group">
<lable>Password</lable>
<input type="text" th:field="*{password}">
</div>
<button type="submit">Login</button>
</form>
</body>
</html>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/login?useSSL=false&serverTimezone=UTC&useLegacyDatetimecode=false
spring.datasource.username=root
spring.datasource.password=123123
#Hibernate
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate auto ddl
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

Related

Display user name in Spring

I can login and logout, and display a list of users on a page doing this:
<li th:each="user : ${users}">
<span th:text="${user.firstname}+' '+${user.lastname}"></span>
</li>
I would now simply like to display the name of the currently logged in user, but I am not sure how. I would like to add it to a header fragment so every page shows clearly who the user logged in is.
LoginForm.java:
package com.demo.spring.domain;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginForm {
public String getAccountname() {
return accountname;
}
public void setAccountname(String accountname) {
this.accountname = accountname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#NotEmpty
String accountname;
#NotEmpty
String password;
}
login.html:
<h3>User Login</h3>
<form action="#" th:action="#{/user/login}" th:object="${user}" method="post">
<!--<input type="hidden" th:field="*{id}"/>-->
<p>Account Name:</p> <input type="text" th:field="*{accountname}"/>
<p>Password:</p> <input type="password" th:field="*{password}"/>
<p/><input type="submit" value="Login"/>
</form>
<div th:if="${message!=null}">
<br/>
<span th:text="${message}"/>
</div>
UserController code for logging in:
package com.demo.spring.controller;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
#Controller
#RequestMapping(value = "/user")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginView(Model model)
{
LoginForm user = new LoginForm();
model.addAttribute("user", user);
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
if(bindingResult.hasErrors())
{
model.addAttribute("user", user);
model.addAttribute("message", "Please provide information in each field");
return "login";
}
if (userService.validateLogin(user)==false)
{
model.addAttribute("user", user);
model.addAttribute("message", "Your accountname and/or password are incorrect");
return "login";
}
session.setAttribute("login", true);
return "redirect:/";
}
UserService
package com.demo.spring.service;
import com.demo.spring.domain.LoginForm;
import com.demo.spring.domain.UserSearchForm;
import com.demo.spring.domain.User;
import com.demo.spring.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
public boolean validateLogin(LoginForm user)
{
List<User> users = userRepository.checkUserInput(user.getAccountname(),user.getPassword());
return users !=null && users.size()>0;
}
We put the logged in users' name in the session
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, #Valid #ModelAttribute("user") LoginForm user, BindingResult bindingResult, HttpSession session)
{
...
session.setAttribute("accountName", user.getAccountName());
session.setAttribute("login", true);
return "redirect:/";
}
Once put in the session, the session variables can simply be accessed as ${session.accountName}. So you can use <span th:text="${session.accountName}"></span> in your header fragment.

Invalid property 'idUtilisateur' of bean class

I'm getting following error while running my Spring MVC web application:
Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
How can I fix it?
Utilisateur.java
package com.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idutilisateur")
private Long idUtilisateur;
#Column(name="emailutilisateur")
private String emailUtilisateur;
#Column(name="motpasseutilisateur")
private String motPasseUtilisateur;
#Column(name="nomutilisateur")
private String nomUtilisateur;
#Column(name="dateinscriptionutilisateur")
private Timestamp dateInscriptionUtilisateur;
public Long getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(Long idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getEmailUtilisateur() {
return emailUtilisateur;
}
public void setEmailUtilisateur(String emailUtilisateur) {
this.emailUtilisateur = emailUtilisateur;
}
public String getMotPasseUtilisateur() {
return motPasseUtilisateur;
}
public void setMotPasseUtilisateur(String motPasseUtilisateur) {
this.motPasseUtilisateur = motPasseUtilisateur;
}
public String getNomUtilisateur() {
return nomUtilisateur;
}
public void setNomUtilisateur(String nomUtilisateur) {
this.nomUtilisateur = nomUtilisateur;
}
public Timestamp getDateInscriptionUtilisateur() {
return dateInscriptionUtilisateur;
}
public void setDateInscriptionUtilisateur(Timestamp dateInscriptionUtilisateur) {
this.dateInscriptionUtilisateur = dateInscriptionUtilisateur;
}
#Override
public String toString() {
return "Utilisateur [idUtilisateur=" + idUtilisateur + ", emailUtilisateur=" + emailUtilisateur
+ ", motPasseUtilisateur=" + motPasseUtilisateur + ", nomUtilisateur=" + nomUtilisateur
+ ", dateInscriptionUtilisateur=" + dateInscriptionUtilisateur + "]";
}
}
UtilisateurController
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.model.Utilisateur;
import com.service.UtilisateurService;
#Controller
public class UtilisateurController {
#SuppressWarnings("unused")
private final static Logger logger = Logger.getLogger("UtilisateurController");
public UtilisateurController(){
System.out.println("spring_da_user_management_web_app");
}
#Autowired
private UtilisateurService service;
#RequestMapping(value="/newUtilisateur", method=RequestMethod.GET)
public ModelAndView newUtilisateur(ModelAndView model){
Utilisateur utilisateur = new Utilisateur();
model.addObject("utilisateur", utilisateur);
model.setViewName("utilisateurForm");
return model;
}
#RequestMapping(value = "/saveUtilisateur", method = RequestMethod.POST)
public ModelAndView saveUtilisateur(#ModelAttribute Utilisateur utilisateur) {
if (utilisateur.getIdUtilisateur() == 0) {
service.addUtilisateur(utilisateur);
} else {
service.updateUtilisateur(utilisateur);
}
return new ModelAndView("redirect:/");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView listeUtilisateur(ModelAndView model) throws IOException{
List<Utilisateur> listeUtilisateur = service.getAllUtilisateur();
model.addObject("listeUtilisateur", listeUtilisateur);
model.setViewName("listeutilisateur");
return model;
}
#RequestMapping(value = "/editUtilisateur", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
Long idUtilisateur = Long.parseLong(request.getParameter("idUtilisateur"));
Utilisateur utilisateur = service.getUtilisateurById(idUtilisateur);
ModelAndView model = new ModelAndView("utilisateurForm");
model.addObject("utilisateur", utilisateur);
return model;
}
#RequestMapping(value="/deleteUtilisateur", method=RequestMethod.GET)
public ModelAndView deleteUtilisateur(HttpServletRequest request){
service.deleteUtilisateur(Long.parseLong(request.getParameter("idUtilisateur")));
return new ModelAndView("redirect:/");
}
}
UtilisateurDao
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.Utilisateur;
#Repository
public class UtilisateurDaoImpl implements UtilisateurDao {
#Autowired
private SessionFactory sessionFactory;
public void addUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().saveOrUpdate(utilisateur);
}
#SuppressWarnings("unchecked")
public List<Utilisateur> getAllUtilisateur() {
List<Utilisateur> listeUtilisateur = sessionFactory.getCurrentSession().createQuery("from Utilisateur").list();
return listeUtilisateur;
}
public Utilisateur getUtilisateurById(Long idUtilisateur) {
return (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
}
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().update(utilisateur);
return utilisateur;
}
public void deleteUtilisateur(Long idUtilisateur) {
Utilisateur utilisateur = (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
if(utilisateur != null){
this.sessionFactory.getCurrentSession().delete(utilisateur);
}
}
}
utilisateurForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit / Save Utilisateur</title>
</head>
<body>
<div align="center">
<h1> Edit / Save Utilisateur</h1>
<form:form action="saveUtilisateur" method="post" modelAttribute="utilisateur">
<table>
<form:hidden path="idUtilisateur"/>
<tr>
<td>Adresse email</td>
<td><form:input path="emailUtilisateur"/></td>
</tr>
<tr>
<td>Mot de passe</td>
<td><form:password path="motPasseUtilisateur"/></td>
</tr>
<tr>
<td>Nom d'utilisateur</td>
<td><form:input path="nomUtilisateur"/></td>
</tr>
<tr>
<td>Date d'inscription</td>
<td><form:input path="dateInscriptionUtilisateur"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

Why is not null error message displaying before form submission?

I've created basic form validation in Spring using annotations. For unknown reason it is displaying the NotNull error message I specified in the User class before the form is submitted. Any ideas why?
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="springForm" %>
<%# page session="false" %>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Home</title>
</head>
<body>
<springForm:form method="POST" action="#" commandName="user" >
<table>
<tr>
<td>UserName:</td>
<td><springForm:input path="userName" /></td>
<td><springForm:errors path="userName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Save Changes" />
</td>
</tr>
</table>
</springForm:form>
</body>
</html>
package com.journaldev.spring;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
public class User {
private int id;
#NotNull #Size(min=2, max=30)
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User(){
}
}
package com.journaldev.spring;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
public String home(Model model, #Valid User user,
BindingResult bindingResult) {
return "home";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Locale locale, Model model) {
return "login";
}
#RequestMapping(value = "/home", method = RequestMethod.POST)
public String login(#Validated User user, Model model) {
model.addAttribute("userName", user.getUserName());
return "user";
}
}
You have same method on "/" for GET and POST with #Valid and BindingResult. Create separate method for GET without parameters you don't need there.

Passing String from jsp to Controller in Spring

I created a project with Spring + JPA + Hibernate. I want to pass a string from jsp to controller(removeUtente method). If I click on the link I delete the row from the database .. Where am I doing wrong? Excuse me for my english..The controller receives the string from jsp and calls the method to remove it.
Thanks
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Lista utenti</h2>
<table border="1">
<c:forEach var="utente" items="${lista }">
<tr>
<td>
<c:out value="${utente.id}"/>
</td>
<td>
<c:out value="${utente.cognome}"/>
</td>
<td>
<c:out value="${utente.nome}"/>
</td>
<td>
<c:out value="${utente.eta}"/>
</td>
<td>
<c:url var="url" value="/remove">
<c:param name="id" value="${utente.id }"/>
</c:url>
click to delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
UtenteController.java
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import persistence.UtenteDAO;
import bean.Utente;
#Controller
public class UtenteController {
#Autowired
UtenteDAO utenteDAO;
#RequestMapping(value="/add",method=RequestMethod.POST)
public String addUtente(#ModelAttribute Utente u){
utenteDAO.inserisciUtente(u);
return "index";
}//addUtente
#RequestMapping(value="/show",method=RequestMethod.GET)
public String getUtenti(ModelMap model){
List<Utente> lista=utenteDAO.listaUtenti();
model.addAttribute("lista", lista);
return "showlista";
}//getUtenti
#RequestMapping(value="/remove",method=RequestMethod.GET)
public String removeUtente(#RequestParam String id){
utenteDAO.rimuovi(id);
return "showlista";
}//removeUtente
}//UtenteController
Utente.java
package bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utente")
public class Utente {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#Column(name="cognome")
private String cognome;
#Column(name="nome")
private String nome;
#Column(name="eta")
private Integer eta;
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
public String getCognome(){return cognome;}//getCognome
public void setCognome(String cognome){this.cognome=cognome;}//setCognome
public String getNome(){return nome;}//getNome
public void setNome(String nome){this.nome=nome;}//setNome
public Integer getEta(){return eta;}//getEta
public void setEta(Integer eta){this.eta=eta;}//setEta
#Override
public String toString(){
return "id:"+id+" cogn:"+cognome+" nome:"+nome+" eta:"+eta;
}//toString
}//Utente
UtenteDAOImpl.java
package persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import bean.Utente;
#Transactional
public class UtenteDAOImpl implements UtenteDAO {
#PersistenceContext
EntityManager em;
public void inserisciUtente(Utente u){
em.persist(u);
}//inserisciUtente
#SuppressWarnings("unchecked")
public List<Utente> listaUtenti(){
Query q=em.createQuery("SELECT u FROM Utente u");
List<Utente> ris=q.getResultList();
return ris;
}//listaUtenti
public void rimuovi(String idUtente){
Query q=em.createQuery("DELETE FROM Utente AS u WHERE u.id =:id");
q.setParameter("id", idUtente);
q.executeUpdate();
}//rimuovi
}//inserisciUtente

login jsf spring and hibernate error

i'm working on a login application using jsf, spring and hibernate.
I have a problem, i get invalid password and username even if i put valid username and password. i don't understand why. please help me :)
login.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<title>Facelet Title</title>
<link href="http://localhost:8084/jsf/resources/css/login.css" type="text/css" rel="stylesheet"/>
</h:head>
<h:body>
<div class="container">
<h:form id="formLogin">
<p:growl id="growl" sticky="true" showDetail="true" life="3000" />
<p:panel header="Login">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="Username:" />
<p:inputText id="username" value="#{utilisateurBean.utilisateur.username}" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<p:password id="password" value="#{utilisateurBean.utilisateur.password}" required="true" label="password" />
<f:facet name="footer">
<p:commandButton value="Login" update="growl" actionListener="#{utilisateurBean.login(actionEvent)}"
oncomplete="handleLoginRequest(xhr, status, args)" />
</f:facet>
</h:panelGrid>
</p:panel>
</h:form>
</div>
<script type="text/javascript">
function handleLoginRequest(xhr, status, args) {
if(args.validationFailed || !args.loggedIn) {
PF('#formLogin').jq.effect("shake", {times:5}, 100);
}
else {
location.href = args.route;
}
}
</script>
</h:body>
</html>
UtilisateurBean.java
package controller;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import model.services.UtilisateurMetier;
import model.services.UtilisateurMetierImpl;
import net.vo.Utilisateur;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope("view")
public class UtilisateurBean{
private Utilisateur utilisateur;
#Autowired
private UtilisateurMetier utilisateurMetier;
String route = "";
public UtilisateurBean() {
this.utilisateurMetier = new UtilisateurMetierImpl();
if(this.utilisateur == null)
{
this.utilisateur = new Utilisateur();
}
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public void login(ActionEvent actionEvent)
{
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg;
boolean loggedIn;
this.utilisateur = this.utilisateurMetier.verify(this.utilisateur);
if (this.utilisateur != null)
{
loggedIn = true;
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("utilisateur", this.utilisateur.getUsername());
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", this.utilisateur.getUsername());
route ="/jsf/faces/annee.xhtml";
System.out.println(this.utilisateur.getUsername());
} else {
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid mot de passe");
if(this.utilisateur == null)
{
this.utilisateur = new Utilisateur();
}
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
context.addCallbackParam("route", route);
}
}
UtilisateurMetier.java
package model.services;
import java.util.List;
import net.vo.Utilisateur;
public interface UtilisateurMetier {
public Utilisateur verify(Utilisateur utilisateur);
}
UtilisateurMetierImpl.java
package model.services;
import dao.UtilisateurDao;
import java.util.List;
import javax.faces.context.FacesContext;
import net.vo.Utilisateur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UtilisateurMetierImpl implements UtilisateurMetier{
#Autowired
private UtilisateurDao dao;
public void setDao(UtilisateurDao dao) {
this.dao = dao;
}
#Override
public Utilisateur verify(Utilisateur utilisateur)
{
return dao.verify(utilisateur);
}
}
UtilisateurDao.java
package dao;
import java.util.List;
import net.vo.Utilisateur;
public interface UtilisateurDao {
public Utilisateur getUtilisateur(Integer id);
public Utilisateur verify(Utilisateur utilisateur);
}
UtilisateurHibernateDao.java
package dao;
import java.util.List;
import net.vo.Utilisateur;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
#Repository
public class UtilisateurHibernateDao implements UtilisateurDao{
private List<Utilisateur> listeUtilisateurs;
#Override
public Utilisateur getUtilisateur(Integer id) {
Session session = HibernateUtil.getSession();
try
{
session.beginTransaction();
Query q = session.createQuery("from Utilisateur as u where u.idUtilisateur=" + id);
return (Utilisateur) q.uniqueResult();
}
finally
{
session.close();
}
}
#Override
public Utilisateur verify(Utilisateur utilisateur) {
Utilisateur user = this.getUtilisateur(utilisateur.getIdUtilisateur());
if(user != null)
{
if(!utilisateur.getPassword().equals(user.getPassword()))
{
user = null;
}
}
return user;
}
}
Utilisateur.java
package net.vo;
// Generated 21 mai 2014 21:08:45 by Hibernate Tools 3.6.0
/**
* Utilisateur generated by hbm2java
*/
public class Utilisateur implements java.io.Serializable {
private int idUtilisateur;
private String username;
private String password;
public Utilisateur() {
}
public Utilisateur(int idUtilisateur, String username, String password) {
this.idUtilisateur = idUtilisateur;
this.username = username;
this.password = password;
}
public int getIdUtilisateur() {
return this.idUtilisateur;
}
public void setIdUtilisateur(int idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
edit
public void login(ActionEvent actionEvent)
{
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg;
boolean loggedIn;
this.utilisateur = this.utilisateurMetier.verify(this.utilisateur);
if (this.utilisateur != null)
{
loggedIn = true;
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("utilisateur", this.utilisateur.getUsername());
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", this.utilisateur.getUsername());
route ="/jsf/faces/index.xhtml";
System.out.println(this.utilisateur.getUsername());
} else {
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid mot de passe");
if(this.utilisateur == null)
{
this.utilisateur = new Utilisateur();
}
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
context.addCallbackParam("route", route);
}
In UtilisateurHibernateDao#verify you're trying to retrieve the user from its id:
Utilisateur user = this.getUtilisateur(utilisateur.getIdUtilisateur());
But you only have the username ans password. I suggest to create another method that can return the user from its username:
public Utilisateur getUtilisateurByUsername(String username) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
Query q = session.createQuery("from Utilisateur as u where u.username=:username")
.setString("username", username);
return (Utilisateur) q.uniqueResult();
}
finally {
session.close();
}
}
And use this method in verify:
Utilisateur user = this.getUtilisateurByUsername(utilisateur.getUsername());
//rest of the code...
Not part of the main problem but IMO the verify method should be at service level, not at dao. Data Access Objects are meant to only retrieve and update the data to the data source, while the business rules should be in service layer.

Resources