Invalid property 'idUtilisateur' of bean class - spring

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>

Related

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

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

${channels} is empty in JSP page served by Spring MVC

I am new to Java using STS 4 Eclipse, Java 8.
I am trying to use JSTL tags to output some values through my jsp file, however, I am not getting any output from my forEach loop in list.jsp. I am getting an output from the < p > tag directly before the loop.
Sorry for the large amount of code just didn't want to miss anything.
list.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Channels</title>
</head>
<body>
<p>Channels</p>
<c:forEach items="${channels}" var="channel">
<p>${channel.name}'s topic is ${channel.topic}</p>
<p> Link to the channel</p>
</c:forEach>
</body>
</html>
ChannelController.java
package co2103.hw1.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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.bind.annotation.RequestMapping;
import co2103.hw1.Hw1Application;
import co2103.hw1.domain.Channel;
#Controller
public class ChannelController {
public List<Channel> channels;
#GetMapping("/channels")
public String channelsList(Model model) {
model.addAttribute("channels", Hw1Application.channels);
return "channels/list";
}
#RequestMapping("/newChannel")
public String newchannel(Model model) {
model.addAttribute("channel", new Channel());
return "channels/form";
}
#PostMapping("/addChannel")
public String updateChannel(#ModelAttribute Channel channel, BindingResult result) {
if (result.hasErrors()) {
return "channels/form";
}
int id = 0;
channel.setId(id);
String name = null;
channel.setName(name);
String topic = null;
channel.setTopic(topic);
Hw1Application.channels.add(channel);
return "redirect:/";
}
}
Hw1Application
package co2103.hw1;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import co2103.hw1.domain.Channel;
import co2103.hw1.domain.Show;
#SpringBootApplication
public class Hw1Application {
public static void main(String[] args) {
SpringApplication.run(Hw1Application.class, args);
}
public static List<Channel> channels = new ArrayList<>();
public static List<Show> shows = new ArrayList<>();
public void run(String... args) {
Channel channel = new Channel();
channel.setId(0);
channel.setName("Channel 1");
channel.setTopic("Nothing");
Show show = new Show();
show.setTitle("Show 1");
show.setProducer("Me");
show.setCategory("News");
show.setEpisodes(300);
Show show2 = new Show();
show.setTitle("Show 2");
show.setProducer("Me2");
show.setCategory("News2");
show.setEpisodes(300);
shows.add(show);
shows.add(show2);
channel.setShows(shows);
}
}
Channel.java
package co2103.hw1.domain;
import java.util.List;
public class Channel {
private int id;
private String name;
private String topic;
private List<Show> shows;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
}
in the class Hw1Application ==> the method public void run(String... args) :
you need to add in the end
channels.add(channel)
Because in ChannelController.java you called channels ( that is empty in w1Application and not setted) in you #GettingMapping
So the answer that worked for me was to implements CommandLineRunner in my Hw1Application class
Hw1Application.java
#SpringBootApplication
public class Hw1Application implements CommandLineRunner {
....
}

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.

Problems with AccessReferenceMap

I am using AccessReferenceMap from OWASP to secure my ids in URLs. The problem is that when list of IDs to be obfuscated is related to particular customer. Here is my configuration:
<bean id="hyperlinkMapping" class="web.security.HyperlinkMapping" scope="session">
<aop:scoped-proxy />
</bean>
<bean id="tracksAccessMap" class="web.security.EntityAccessMap"
scope="session" factory-method="create">
<constructor-arg index="0" ref="allTrackIdsForCustomer" />
<aop:scoped-proxy/>
</bean>
<bean id="allTrackIdsForCustomer" scope="session"
factory-bean="webTrackDAO"
factory-method="findAllTrackIdsForCustomer">
<aop:scoped-proxy/>
</bean>
<bean id="webTrackDAO" class="web.repository.impl.WebTrackDAOImpl"/>
EntityAccessMap:
package web.security;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.owasp.esapi.AccessReferenceMap;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.reference.RandomAccessReferenceMap;
import org.springframework.stereotype.Component;
import core.domain.Entity;
#Component
public class EntityAccessMap<T extends Entity> implements AccessMap<T> {
private static Logger logger = Logger.getLogger(EntityAccessMap.class);
private static final long serialVersionUID = -436098952674898327L;
private AccessReferenceMap<String> map = new RandomAccessReferenceMap();
public EntityAccessMap() {
}
private EntityAccessMap(final List<T> entities) {
logger.info("Entities size: " + entities.size());
for (final T entity : entities) {
map.addDirectReference(entity);
}
}
public <T extends Entity> AccessMap<T> create(final List<T> entities) {
logger.info("calling create with entities' size " + entities.size() );
return new EntityAccessMap<>(entities);
}
public String getIndirectReference(final T entity) {
for( Iterator it = map.iterator(); it.hasNext(); ) {
logger.info((String)it.next().toString());
}
logger.info("Entity: " + map.getIndirectReference(entity));
return map.getIndirectReference(entity);
}
public T getDirectReference(final String indirectReference) {
try {
return map.getDirectReference(indirectReference);
} catch (AccessControlException e) {
throw new IllegalArgumentException("Indirect Reference is not valid", e);
}
}
}
AccessMap:
package web.security;
import java.io.Serializable;
import core.domain.Entity;
public interface AccessMap<T extends Entity> extends Serializable {
String getIndirectReference(final T entity);
T getDirectReference(final String indirectReference);
}
HyperlinkMapping:
package web.security;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import core.domain.track.Track;
public class HyperlinkMapping implements Serializable {
private static final long serialVersionUID = -2011016815710653498L;
#Autowired AccessMap<Track> tracksAccessMap;
public String getTrackId(final Track track) {
return tracksAccessMap.getIndirectReference(track);
}
public Track getTrack(final String indirectId) {
return tracksAccessMap.getDirectReference(indirectId);
}
}
So, what I want to achieve: tracksAccessMap should be filled only with customer's related ids, not whole set. How to initialize all these beans after customer's login (and setting customerId session attribute)?
EDIT 1: additional code:
TracksController:
package web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import core.constants.WebConstants;
import web.service.TrackService;
#Controller
#Secured("ROLE_USER")
#RequestMapping(WebConstants.WEB_MY)
#Scope("session")
public class TracksController {
#Autowired
private TrackService trackService;
#Autowired
private HyperlinkMapping hyperlinkMapping;
#RequestMapping(value=WebConstants.WEB_MYTRACKS, method = RequestMethod.GET, produces = "application/json")
public ModelAndView showTracks( HttpServletRequest request, #RequestParam(value = "pageSize", required = false) Integer pageSize ) {
ModelAndView mv = new ModelAndView();
mv.addObject("pagedListHolder",trackService.getTracksList(request, pageSize == null ? 10 : pageSize ));
mv.addObject("hyperlinkMapping",hyperlinkMapping);
return mv;
}
}
centerColTracks.jsp
<c:forEach items="${pagedListHolder.pageList}" var="item">
<tr>
<td>${item.id}</td>
<td style="color:blue;text-align:right">${item.name}</td>
<td style="color:blue;text-align:right">${item.trackDate}</td>
<td style="color:blue;text-align:right">${item.description}</td>
</tr>
</c:forEach>
hyperlinkMapping.getTrackId(item) should return ONLY trackId (taken from AccessReferenceMap) related ONLY for customer logged in. In other words - hyperlinkMapping should be instantiated right after the login.
I have two ideas how to do this: 1. AOP with after-returning advice, or 2. use SimpleUrlAuthenticationSuccessHandler, where I can instantiate HyperlinkMapping after login. Or I can use it with the current implementation and I just simply forgot something?

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