can JSF Still data user login? - jsf

Hello all i have one problem between 2 class of JSF Manage bean.
i have 2 class JSF Manage bean one class use for login, one use for user add/edit/delete user table and edit his information when his login.
my login class
import com.DAO.UserBean;
import com.entity.IUser;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* #author MYE
*/
#ManagedBean
#SessionScoped
public class LoginController implements Serializable{
#EJB
private UserBean userBean;
private IUser user;
private boolean admin ;
private boolean mod ;
/** Creates a new instance of LoginController */
public LoginController() {
user = new IUser();
}
//getter / setter
public boolean isMod() {
return mod;
}
public void setMod(boolean mod) {
this.mod = mod;
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public boolean isAdmin() {
return admin ;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public String cplogin() {
if (userBean.userLogin(user.getUsername(), user.getPassword()) != null) {
if(user.getUsername() != null || user.getPassword() != null){
user = userBean.userLogin(user.getUsername(), user.getPassword());
if(user.getGroups().getAdmin() != null){
setAdmin(user.getGroups().getAdmin());
}
if(user.getGroups().getMods() != null){
setMod(user.getGroups().getMods());
}
if(isAdmin() == true || isMod() == true){
return "home";
}else{
return "login";
}
}else {
return "login";
}
} else {
return "login";
}
}
public String logout() {
user = null;
return "login";
}
public boolean isLoggedIn() {
return user != null;
}
}
and my user bean
import com.DAO.UserBean;
import com.entity.Groups;
import com.entity.IUser;
import com.entity.UserGender;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
/**
*
* #author Kency
*/
#ManagedBean
#ViewScoped
public class UserController implements Serializable{
#EJB
private UserBean userBean;
private IUser user;
private LoginController loginsController;
private Groups groups;
private List<SelectItem> enumGender = new ArrayList<SelectItem>();
private UserGender userGender;
public List<SelectItem> getEnumGender() {
return enumGender;
}
public void setEnumGender(List<SelectItem> enumGender) {
this.enumGender = enumGender;
}
public UserGender getUserGender() {
return userGender;
}
public void setUserGender(UserGender userGender) {
this.userGender = userGender;
}
/** Creates a new instance of UserController */
public UserController() {
user = new IUser();
loginsController = new LoginController();
System.out.println(loginsController.getUser());
for(UserGender iGender : UserGender.values()){
enumGender.add(new SelectItem(iGender, iGender.getLabel()));
}
}
#PostConstruct
public Groups construcGroup(){
return groups = new Groups(1, "Memmber");
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public List<IUser> getUserList(){
return userBean.retrieveAllUser();
}
public void updateUser(){
user = userBean.updateUser(user);
}
public void deleteUser (IUser user){
userBean.deleteUser(user);
}
public void showUserdetails(IUser user){
this.user = user;
}
public IUser getUserDetails(){
return user;
}
public String addUser(){
if(loginsController.isAdmin() == false){
user.setGroups(construcGroup());
if(userBean.checkExistName(user.getUsername()) != null && userBean.checkExistEmail(user.getEmail()) != null
|| userBean.checkExistName(user.getUsername()) != null || userBean.checkExistEmail(user.getEmail()) != null){
checkUserEmail("username or email has exist");
}else{
user = userBean.addUser(user);
addMessage("add success");
return "home";
}
}else {
if(userBean.checkExistName(user.getUsername()) != null && userBean.checkExistEmail(user.getEmail()) != null
|| userBean.checkExistName(user.getUsername()) != null || userBean.checkExistEmail(user.getEmail()) != null){
checkUserEmail("username or email has exist");
}else {
user = userBean.addUser(user);
addMessage("add success");
return "ok";
}
}
return "String";
}
public javax.faces.model.SelectItem[] getGroupList()
{
SelectItem[] options = null;
List<Groups> groups = userBean.retrieveAllGroups();
if (groups != null && groups.size() > 0)
{
int i = 0;
options = new SelectItem[groups.size()];
for (Groups iGroups : groups)
{
options[i++] = new SelectItem(iGroups,iGroups.getGroupname());
}
}
return options;
}
public void checkUserEmail(String msg) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,msg));
}
public void addMessage(String msg) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
}
my question is when i use method isAdmin from loginController for userController to check if he is admin he can choose user groups, if he isn't admin he add default groups is member. but isAdmin from loginController return false why? why it not still data when user login?

You need to inject the bean as a managed property.
#ManagedProperty(value="#{loginController}")
private LoginController loginController;
And get rid of the new LoginController() line in the constructor. It would construct a completely separate instance of the bean, not reuse the already-created one in the session scope.

Related

"#{loginBean.nom}": Target Unreachable, identifier 'loginBean' resolved to null

I try every solution but still have this problem:
/Acceuil.xhtml #19,30 value="#{loginBean.nom}": Target Unreachable, identifier 'loginBean' resolved to null
I use tomcat 7 as server.
Can you help me to find the problem?
i use two bean
this is LoginBean:
package tn.gestiondintervention.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import tn.gestiondintervention.model.Login;
import tn.gestiondintervention.service.LoginService;
import tn.gestiondintervention.service.impl.LoginServiceImpl;
#ManagedBean(name = "loginBean")
#SessionScoped
public class LoginBean {
private List<Login> loginList;
private String nom;
private String matricule;
public List<Login> getLoginList() {
loginList=new ArrayList<Login>();
LoginService loginService= new LoginServiceImpl();
loginList=loginService.listLogin();
return loginList;
}
public void setLoginList(List<Login> loginList) {
this.loginList = loginList;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String authentification()
{
LoginService loginService= new LoginServiceImpl();
Login login=loginService.getLogin(getMatricule());
if (login == null) {
return "erroracceuil";
} else {
if (login.getNom() == "admin")
{
return "succesadmin";
} else
return "succes";
}
}
#SuppressWarnings("null")
public String inscription()
{
LoginService loginService= new LoginServiceImpl();
Login login = loginService.getLogin(getMatricule());
if (login == null){
login.setNom(getNom());
login.setMatricule(getMatricule());
loginService.addLogin(login);
return "inscript";
}
else return "errorinscript";
}
public String listUser(){
return "succeslisteutilisateur";
}
}

Storing a http session attribute in database

How can I pass an injected http session attribute (see below), along with other values (informe by the user) and save them using JPA?
The session attribute is correctly displayed and injected, but I need to pass it using the selected to be stored in the database (actually, it passess null).
The JSF:
<p:outputLabel value="UserID (the sessionAttribute):" for="userID" />
<p:inputText id="userID" value="#{userBean.myUser.xChave}" title="userID" />
<p:outputLabel value="Type the Reason:" for="reason" />
<p:inputText id="reason" value="#{viagensController.selected.reason}" />
<!-- updated (just the call to the action method: -->
<p:commandButton actionListener="#{viagensController.saveNew}" value="#{viagensBundle.Save}" update="display,:ViagensListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,ViagensCreateDialog);" />
The bean:
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
private bean_login myUser;
public bean_login getMyUser() {
return myUser;
}
public void setMyUser(bean_login myUser) {
this.myUser = myUser;
}
#PostConstruct
public void init() {
String uid = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("xChave").toString();
myUser = new bean_login();
myUser.setxChave(uid);
System.out.print("from init:" + myUser.toString());
}
}
The AbstractFacade:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {{ /*impl. ommited*/ }
public List<T> findAll() {{ /*impl. ommited*/ }
public List<T> findRange(int[] range) { /*impl. ommited*/ }
public int count() { /*impl. ommited*/ }
}
The AbstractController (for the selected in JSF above and other methods):
public abstract class AbstractController<T> {
#Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;
private enum PersistAction {
CREATE,
DELETE,
UPDATE
}
public AbstractController() {
}
public AbstractController(Class<T> itemClass) {
this.itemClass = itemClass;
}
public T getSelected() {
return selected;
}
// Pass in the currently selected item
public void setSelected(T selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
public Collection<T> getItems() {
if (items == null) {
items = this.ejbFacade.findAll();
}
return items;
}
// Pass in collection of items
public void setItems(Collection<T> items) {
this.items = items;
}
// Apply changes to an existing item to the data layer.
public void save(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Updated");
persist(PersistAction.UPDATE, msg);
}
// Store a new item in the data layer.
public void saveNew(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Created");
persist(PersistAction.CREATE, msg);
if (!isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void delete(ActionEvent event) {/*implementations ommited*/ }
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException excp = (ConstraintViolationException) cause;
for (ConstraintViolation s : excp.getConstraintViolations()) {
JsfUtil.addErrorMessage(s.getMessage());
}
} else {
msg = cause.getLocalizedMessage();
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/viagensBundle").getString("PersistenceErrorOccured"));
}
}
}
// Creates a new instance of an underlying entity and assigns it to Selected property.
public T prepareCreate(ActionEvent event) {
T newItem;
try {
newItem = itemClass.newInstance();
this.selected = newItem;
initializeEmbeddableKey();
return newItem;
} catch (InstantiationException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// Inform the user interface whether any validation error exist on a page.
public boolean isValidationFailed() {
return JsfUtil.isValidationFailed();
}
// Retrieve all messages as a String to be displayed on the page.
public String getComponentMessages(String clientComponent, String defaultMessage) {
return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
}
Thanks in advance.
updated:
The ViagensController:
#Named(value = "viagensController")
#ViewScoped
public class ViagensController extends AbstractController<Viagens> implements Serializable {
//generics:passing JPA Entity class, where the 'reason' in JSF is defined
public ViagensController() {
super(Viagens.class);
}
}
Need to override the save method passing the injected http session value :
#ManagedBean(name = "riscosController")
#ViewScoped
public class RiscosController extends AbstractController<Riscos> {
#EJB
private RiscosFacade ejbFacade;
#Inject
#SessionChave
private String iSessionChave;
private String sessionChave;
private UorPosController matriculaController;
private UorPosController informanteController;
public String getSessionChave(String chave) {
if (sessionChave.isEmpty()) {
sessionChave = iSessionChave;
}
return sessionChave;
}
public void setSessionChave(String sessionChave) {
this.sessionChave = sessionChave;
}
#PostConstruct
#Override
public void init() {
super.setFacade(ejbFacade);
FacesContext context = FacesContext.getCurrentInstance();
matriculaController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
informanteController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
sessionChave = "";
}
#Override
public void saveNew(ActionEvent event) {
this.getSelected().setObs(this.getSessionChave(sessionChave));
super.saveNew(event);
}
}

primefaces autocomplete not showing in textBox

I have tried to implement the autocomplete feature in primefaces but suggestions do not show up in my textbox. Can someone show me what I'm missing. theses are codes
udateCategory.xhtml
<p:panel header="Type in Category to Edit" >
<p:outputLabel value="Category Name"/>
<p:autoComplete value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{catConverter}"
forceSelection="true"/>
<p:commandButton value="Update" action="#{category.saveCategory}"/>
</p:panel>
CategoryBean
public class CategoryBean implements Serializable{
private Category selectedCategory;
/**
* Creates a new instance of CategoryBean
*/
public CategoryBean() {
}
public List<Category> completeCategory (String query){
CategoryManager manager = new CategoryManager();//an instance of the manager
List<Category> suggestions = new ArrayList<>();//an instance of list
List<Category> allCategory = new ArrayList<>(); //populate the allCategory with data fro db
allCategory = manager.getAllCategory();
//checck to see if data exist in allCategory
if(!allCategory.isEmpty()){
System.out.println("kobla : allcategory has data");
}
else
{
System.out.println("kobla: no data in alcategory");
}
for(Category cat : allCategory){
if(cat.getCategoryName().startsWith(query)){
suggestions.add(cat);
}
}
//check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
CategoryConverter
public class CategoryConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
this works for me
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class CategoryBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Category selectedCategory;
#PostConstruct
public void init(){
selectedCategory = new Category();
}
public void saveCategory(){
System.out.println("saved "+this.selectedCategory);
}
public List<Category> completeCategory(String query) {
CategoryManager manager = new CategoryManager();// an instance of the
// manager
List<Category> suggestions = new ArrayList<>();// an instance of list
List<Category> allCategory = new ArrayList<>(); // populate the
// allCategory with data
// fro db
allCategory = manager.getAllCategory();
// checck to see if data exist in allCategory
if (!allCategory.isEmpty()) {
System.out.println("kobla : allcategory has data");
} else {
System.out.println("kobla: no data in alcategory");
}
for (Category cat : allCategory) {
if (cat.getCategoryName().startsWith(query)) {
suggestions.add(cat);
}
}
// check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory
* the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
and
import java.io.Serializable;
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int categoryID;
private String categoryName;
public int getCategoryID() {
return categoryID;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Category(int categoryID, String categoryName) {
super();
this.categoryID = categoryID;
this.categoryName = categoryName;
}
public Category() {
super();
}
#Override
public String toString() {
return "Category [categoryID=" + categoryID + ", categoryName="
+ categoryName + "]";
}
}
and
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
#ManagedBean
#RequestScoped
public class CategoryConverter implements Converter, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form>
<p:outputLabel value="Category Name" />
<p:autoComplete
value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{categoryConverter}"
forceSelection="true" />
<p:commandButton value="Update" action="#{categoryBean.saveCategory}" />
</h:form>
</h:body>
</html>

Transactions in JSF Netbeans 7.3.1 generated code

I'm new to Java EE, following the learning by doing approach. In a very simple Mysql database with Netbeans 7.3.1 having a Patient table relates to a Person table, I'm having trouble understanding Netbeans generated code. I want to create a transaction where a Person and a Patient should be created and persisted with roll back possibility. Should i create a separate controller to handle such a transaction. Kindly help with a link to some similar example code. Code generated by Netbeans is below. (Some imports and redundant code removed)
Person.java
package entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "person")
#XmlRootElement
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "firstname")
private String firstname;
#Size(max = 255)
#Column(name = "email")
private String email;
#Size(max = 15)
#Column(name = "mobile")
private String mobile;
#Size(max = 15)
#Column(name = "residence")
private String residence;
#Size(max = 15)
#Column(name = "office")
private String office;
#Size(max = 255)
#Column(name = "address")
private String address;
#Size(max = 20)
#Column(name = "nic")
private String nic;
#Basic(optional = false)
#NotNull
#Column(name = "regdate")
#Temporal(TemporalType.DATE)
private Date regdate;
#Basic(optional = false)
#NotNull
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "lastname")
private String lastname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 25)
#Column(name = "city")
private String city;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
private Collection<Patient> patientCollection;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Person(Integer id, String firstname, Date regdate, Date dob, String lastname, String city) {
this.id = id;
this.firstname = firstname;
this.regdate = regdate;
this.dob = dob;
this.lastname = lastname;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getResidence() {
return residence;
}
public void setResidence(String residence) {
this.residence = residence;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlTransient
public Collection<Patient> getPatientCollection() {
return patientCollection;
}
public void setPatientCollection(Collection<Patient> patientCollection) {
this.patientCollection = patientCollection;
}
}
Patient.java
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "patient")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p"),
#NamedQuery(name = "Patient.findById", query = "SELECT p FROM Patient p WHERE p.id = :id"),
#NamedQuery(name = "Patient.findByPatientcode", query = "SELECT p FROM Patient p WHERE p.patientcode = :patientcode"),
#NamedQuery(name = "Patient.findByHistory", query = "SELECT p FROM Patient p WHERE p.history = :history"),
#NamedQuery(name = "Patient.findByExtPatientCode", query = "SELECT p FROM Patient p WHERE p.extPatientCode = :extPatientCode")})
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "patientcode")
private String patientcode;
#Size(max = 255)
#Column(name = "history")
private String history;
#Size(max = 20)
#Column(name = "ExtPatientCode")
private String extPatientCode;
#JoinColumn(name = "personid", referencedColumnName = "id")
#ManyToOne(optional = false)
private Person personid;
public Patient() {
}
public Patient(Integer id) {
this.id = id;
}
public Patient(Integer id, String patientcode) {
this.id = id;
this.patientcode = patientcode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPatientcode() {
return patientcode;
}
public void setPatientcode(String patientcode) {
this.patientcode = patientcode;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
public String getExtPatientCode() {
return extPatientCode;
}
public void setExtPatientCode(String extPatientCode) {
this.extPatientCode = extPatientCode;
}
public Person getPersonid() {
return personid;
}
public void setPersonid(Person personid) {
this.personid = personid;
}
}
AbstractFacade.java
package session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
}
PatientFacade.java
package session;
import entity.Patient;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PatientFacade extends AbstractFacade<Patient> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PatientFacade() {
super(Patient.class);
}
}
PersonFacade.java
package session;
import entity.Person;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
PersonController.java
package controllers;
import entity.Person;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PersonFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("personController")
#SessionScoped
public class PersonController implements Serializable {
private Person current;
private DataModel items = null;
#EJB
private session.PersonFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PersonController() {
}
public Person getSelected() {
if (current == null) {
current = new Person();
selectedItemIndex = -1;
}
return current;
}
private PersonFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Person();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Person getPerson(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Person.class)
public static class PersonControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PersonController controller = (PersonController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "personController");
return controller.getPerson(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
}
}
PatientController.java
package controllers;
import entity.Patient;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PatientFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("patientController")
#SessionScoped
public class PatientController implements Serializable {
private Patient current;
private DataModel items = null;
#EJB
private session.PatientFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PatientController() {
}
public Patient getSelected() {
if (current == null) {
current = new Patient();
selectedItemIndex = -1;
}
return current;
}
private PatientFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Patient();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Patient getPatient(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Patient.class)
public static class PatientControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PatientController controller = (PatientController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "patientController");
return controller.getPatient(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Patient) {
Patient o = (Patient) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Patient.class.getName());
}
}
}
}
Thanks in advance.
Fact: a single #Stateless EJB method call counts as a single full transaction.
Just make use of this fact. Create a new method in the #Stateless EJB which executes all necessary queries at once and then let your JSF backing bean call exactly that single method.
That's by the way exactly one of main reasons why EJBs exist: transparent transaction management. You seem to have missed this not unimportant fact while learning Java EE.

JSF: method not found

I'm getting this error while developping my application
javax.el.MethodNotFoundException: /test.xhtml #18,99
action="#{ComplexeController.saveComplexe}": Method not found:
fr.code.parc.controller.ComplexeController#97aead.saveComplexe()
test.xhtml :
<h:body>
<h1>Génération des Complexes</h1>
<h:form>
Nom Complexe: <h:inputText value="#{ComplexeController.complexe.nomComp}"/><br/>
Nom Zone: <h:selectOneMenu id="nomZone" value="#{ComplexeController.complexe.zoneParc}" converter="#{GenericConverter}">
<f:selectItems value="#{ZoneController.remplireItem()}"/>
</h:selectOneMenu>
<br/>
<h:commandButton action="#{ComplexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{ComplexeController.updateComplexe}" value="Modifier un complexe"/>
<br/>
<h:commandLink action="complexe" value="acceuil"/>
</h:form>
</h:body>
the entity Complexe.java
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Complexe generated by hbm2java
*/
#Entity
#Table(name="COMPLEXE"
,schema="PROJET"
)
public class Complexe implements java.io.Serializable {
private String nomComp;
private ZoneParc zoneParc;
private Set<Parc> parcs = new HashSet<Parc>(0);
public Complexe() {
}
public Complexe(String nomComp) {
this.nomComp = nomComp;
}
public Complexe(String nomComp, ZoneParc zoneParc, Set<Parc> parcs) {
this.nomComp = nomComp;
this.zoneParc = zoneParc;
this.parcs = parcs;
}
#Id
#Column(name="NOM_COMP", unique=true, nullable=false, length=30)
public String getNomComp() {
return this.nomComp;
}
public void setNomComp(String nomComp) {
this.nomComp = nomComp;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="NOM_ZONEE")
public ZoneParc getZoneParc() {
return this.zoneParc;
}
public void setZoneParc(ZoneParc zoneParc) {
this.zoneParc = zoneParc;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="complexe")
public Set<Parc> getParcs() {
return this.parcs;
}
#Override
public int hashCode() {
int hash = 0;
hash += (nomComp != null ? nomComp.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 Complexe)) {
return false;
}
Complexe other = (Complexe) object;
if ((this.nomComp == null && other.nomComp != null) || (this.nomComp != null && !this.nomComp.equals(other.nomComp))) {
return false;
}
return true;
}
public void setParcs(Set<Parc> parcs) {
this.parcs = parcs;
}
}
and now ComplexeDaoImpl.java
import config.HibernateUtil;
import fr.code.parc.model.Complexe;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* #author raddaouirami
*/
public class ComplexeDaoImpl implements ComplexeDao{
#Override
public List<Complexe> list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
List complexes = session.createQuery("from Complexe").list();
t.commit();
return complexes;
}
#Override
public Complexe getComplexe(String nomComp) {
Session session = HibernateUtil.getSessionFactory().openSession();
return (Complexe) session.load(Complexe.class, nomComp);
}
#Override
public void save(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.save(complexe);
t.commit();
}
#Override
public void update(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.update(complexe);
t.commit();
}
#Override
public void remove(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.delete(complexe);
t.commit();
}
}
and Finally ComplexeController.java
import fr.code.parc.dao.ComplexeDao;
import fr.code.parc.dao.ComplexeDaoImpl;
import fr.code.parc.model.Complexe;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* #author raddaouirami
*/
#ManagedBean
#SessionScoped
public class ComplexeController {
private Complexe complexe;
private DataModel listeComplexes;
private int selectedItemIndex;
/**
* Creates a new instance of ComplexeController
*/
public ComplexeController() {
complexe = new Complexe();
}
/* public Complexe getSelected() {
if (complexe == null) {
complexe = new Complexe();
selectedItemIndex = -1;
}
return complexe;
}*/
public DataModel getListeComplexes() {
List<Complexe> liste = new ComplexeDaoImpl().list();
listeComplexes = new ListDataModel(liste);
return listeComplexes;
}
/**
* #return the complexe
*/
public Complexe getComplexe() {
return complexe;
}
/**
* #param complexe the complexe to set
*/
public void setComplexe(Complexe complexe) {
this.complexe = complexe;
}
public String preparationAddComplexe(){
setComplexe(new Complexe());
return "test";
}
public String preparationEditComplexe(){
setComplexe((Complexe)(getListeComplexes().getRowData()));
return "test";
}
public String DeleteComplexe(){
Complexe complexes = (Complexe)(getListeComplexes().getRowData());
ComplexeDao dao = new ComplexeDaoImpl();
dao.remove(complexes);
return "complexe";
}
public String SaveComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.save(getComplexe());
return "complexe";
}
public String UpdateComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.update(complexe);
return "complexe";
}
}
How can I solve it?
In view you invoke saveComplexe
action="#{ComplexeController.saveComplexe}"
ComplexeController has only SaveComplexe method.
Either change to
action="#{ComplexeController.SaveComplexe}"
or rename method in ComplexeController to saveComplexe
2 Solutions:
Solution 1.
Change in test.xhtml : complexeController.saveComplexe [Notice first letter in complexeController is in smaller case]
<h:commandButton action="#{complexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{complexeController.updateComplexe}" value="Modifier un complexe"/>
Solution 2.
Change in ComplexeController.java:
#ManagedBean(name="ComplexeController ")
#SessionScoped
public class ComplexeController {
....
}
Read the Following Info about Configuring ManagedBeans in JSF:
There are 2 ways to use #ManagedBean to expose a Java Bean class to Managed Bean class.
Way 1.
#ManagedBean
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{complexeController}
Way 2.
#ManagedBean(name="myBean")
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{myBean}
Try to access the ManagedBean with first char to low case
e.g.
action="#{complexeController.saveComplexe}"
instead of
action="#{ComplexeController.saveComplexe}"

Resources