login jsf spring and hibernate error - spring

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.

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 {
....
}

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>

Java MessageDriven Beans Issue

i need help with this kind of issue:
Exception attempting to inject Unresolved Message-Destination-Ref web.News/queue#java.lang.String#null into class web.News: Lookup failed for 'java:comp/env/web.News/queue' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
This is my Entity Class
package ejb;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author Maciej1
*/
#Entity
public class NewsItem implements Serializable {
private String heading;
private String body;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof NewsItem)) {
return false;
}
NewsItem other = (NewsItem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejb.NewsItem[ id=" + id + " ]";
}
/**
* #return the heading
*/
public String getHeading() {
return heading;
}
/**
* #param heading the heading to set
*/
public void setHeading(String heading) {
this.heading = heading;
}
/**
* #return the body
*/
public String getBody() {
return body;
}
/**
* #param body the body to set
*/
public void setBody(String body) {
this.body = body;
}
}
here is my Message-Driven Beans class:
package ejb;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Maciej1
*/
#MessageDriven(mappedName = "jms/NewsQueue", activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class NewsMDB implements MessageListener {
#PersistenceContext(unitName = "MDBLabPU")
private EntityManager em;
public NewsMDB() {
}
#Override
public void onMessage(Message message) {
ObjectMessage msg = null;
try {
if (message instanceof ObjectMessage) {
msg = (ObjectMessage) message;
NewsItem e = (NewsItem) msg.getObject();
saveObject(e);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
public void saveObject(Object object) {
em.persist(object);
}
}
In the end my class to communication with JavaServer Faces:
package web;
import ejb.NewsItem;
import ejb.NewsItemFacadeLocal;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
/**
*
* #author Maciej1
*/
#Named
#RequestScoped
public class News {
#EJB
private NewsItemFacadeLocal newsItemFacade;
#Resource(lookup="java:comp/DefaultJMSConnectionFactory")
private ConnectionFactory connectionFactory;
#Resource(lookup="jms/NewsQueue")
private javax.jms.Queue queue;
private String headingText = "headingText";
private String bodyText = "bodyText";
void sendNewsItem(String heading, String body)
{
try {
Connection connection = connectionFactory.createConnection();
Session session;
session = connection.createSession(true, 0);
MessageProducer messageProducer = session.createProducer(queue);
ObjectMessage message = session.createObjectMessage();
NewsItem e = new NewsItem();
e.setHeading(heading);
e.setBody(body);
message.setObject(e);
messageProducer.send(message);
messageProducer.close();
connection.close();
} catch (JMSException
ex) {
ex.printStackTrace();
}
}
public List<NewsItem> getNewsItems()
{
return newsItemFacade.findAll();
}
public String submitNews(){
sendNewsItem(getHeadingText(), getBodyText());
return null;
}
Can you help me with this issue?
I discover that problem can be probable in Faces file:
<?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://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:outputText></h:outputText>
<h:inputText value="#{news.headingText}" id="headingInputText"></h:inputText>
<h:outputText></h:outputText>
<h:inputText value="#{news.bodyText}" id="bodyInputText"></h:inputText>
<h:commandButton value="Submit" id="submitButton"></h:commandButton>
</h:form>
</h:body>
</html>
I had to change from this declaration:
#Resource(lookup="jms/NewsQueue")
private javax.jms.Queue queue;
to this:
#Resource(lookup="java:app/jms/NewsQueue")
private javax.jms.Queue queue;
It's generate from NetBeans 8.1 probably differently. Now this code work perfectly

JSF holds the values in components in different users

I'm new in JSF, and I'm trying to use JSF 2 and Richfaces + Spring (3.2.3) + Hibernate (3.6). The application server is JBoss 7.1. The problem is when I deploy my application and use it in my computer it works well, but when I use it in another computer in my LAN or other browser in my same computer, all the values stored in the first use are set in all the fields. I have to say that the application works well but it seems that one user is using it even if I use it in different computers at the same time.
I also deployed it in Cloudbees but it has the same problem through internet.
PD. I searched other similar questions but I couldn't find an answer.
My login.xhtml:
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Usuario "/>
<h:inputText id="txt_usuario" value="#{login.usuario}" required="true" requiredMessage="Debe ingresar su usuario."/><br/>
<h:message for="txt_usuario" />
<h:outputLabel value="Password "/>
<h:inputSecret id="pwd_password" value="#{login.password}" required="true" requiredMessage="Debe ingresar su password."/><br/>
<h:message for="pwd_password" />
</h:panelGrid>
<h:commandButton value="Login" action="#{login.iniciarSesion()}"/>
</h:form>
package com.ejemplo.app.controller;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.PostActivate;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ejemplo.app.entidades.Usuario;
import com.ejemplo.app.service.UsuarioService;
import com.ejemplo.app.util.Constantes;
#Component("login")
#ManagedBean(name = "login")
#SessionScoped
public class LoginController {
#Autowired
private UsuarioService usuarioService;
private String usuario;
private String password;
public LoginController() {
}
public String iniciarSesion() {
try {
Usuario login = usuarioService.validarIngreso(usuario, password);
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.getApplication().createValueBinding("#{sessionScope.user}").setValue(facesContext, login);
if(login.getTipo().equalsIgnoreCase(Constantes.CARGO_RESIDENTE))
return "residente/home";
else if(login.getTipo().equalsIgnoreCase(Constantes.CARGO_LOGISTICA))
return "logistica/home";
else if(login.getTipo().equalsIgnoreCase(Constantes.CARGO_ADMINISTRADOR))
return "administrador/home";
else
System.err.println("Usuario no encontrado.");
} catch (Exception e) {
System.err.println(e.getMessage());
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuario no encontrado.", "Descripcion del mensaje."));
}
return "solicitud_materiales";
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Resources