I have a form with a selectOneMenu with two option and one inputText that which must be disabled if user choose the second option. I think that I should use ajax with update of inputText and is what I did, but don't work. Here is my code, please help me. Thanks
<h:outputText value="Modalita"></h:outputText>
<p:selectOneMenu value="#{vociCostoBean.selected.modalita}" immediate="true">
<f:selectItem itemLabel="Importo" itemValue="0"/>
<f:selectItem itemLabel="Quantita" itemValue="1"/>
<p:ajax update="uc" />
</p:selectOneMenu>
<h:outputText value="Costo Unitario"></h:outputText>
<p:inputText id="uc" disabled="#{vociCostoBean.selected.modalita !='1'}" value="#{vociCostoBean.selected.CUnitario}" />
<br></br>
and this vociCostoBean:
#ManagedBean
#SessionScoped
public class VociCostoBean {
#EJB
private CostoBeanRemote cust;
private List<VociCosto> list;
private VociCosto selected= new VociCosto();
private boolean UcDisabled=true;
#PostConstruct
public void init(){
setList(new ArrayList<VociCosto>());
setList(cust.getAll());
//selected.setModalita("0");
}
public String newCosto(){
return "editCosto";
}
public void onRowSelect(){
FacesContext fc = FacesContext.getCurrentInstance();
System.out.println("|||||"+ getSelected().getNome());
try {
fc.getExternalContext().redirect("editCosto.jsf");
} catch (IOException e) {
}
}
public VociCosto getSelected() {
return selected;
}
public void setSelected(VociCosto selected) {
this.selected = selected;
}
public void setCust(CostoBeanRemote cust) {
this.cust = cust;
}
public List<VociCosto> getList() {
return list;
}
public void setList(List<VociCosto> list) {
this.list = list;
}
public boolean isUcDisabled() {
return UcDisabled;
}
public void setUcDisabled(boolean ucDisabled) {
this.UcDisabled = ucDisabled;
}
}
and this is VociCosto.java
package it.bway.timerep.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Set;
/**
* The persistent class for the VOCI_COSTO database table.
*
*/
#Entity
#Table(name="VOCI_COSTO")
public class VociCosto implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID_COSTO", unique=true, nullable=false)
private int idCosto;
#Column(name="C_UNITARIO")
private int cUnitario;
#Column(length=1)
private String modalita;
#Column(length=50)
private String nome;
//bi-directional many-to-one association to NoteSpese
#OneToMany(mappedBy="vociCosto", fetch=FetchType.EAGER)
private Set<NoteSpese> noteSpeses;
public VociCosto() {
}
public int getIdCosto() {
return this.idCosto;
}
public void setIdCosto(int idCosto) {
this.idCosto = idCosto;
}
public int getCUnitario() {
return this.cUnitario;
}
public void setCUnitario(int cUnitario) {
this.cUnitario = cUnitario;
}
public String getModalita() {
return this.modalita;
}
public void setModalita(String modalita) {
this.modalita = modalita;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Set<NoteSpese> getNoteSpeses() {
return this.noteSpeses;
}
public void setNoteSpeses(Set<NoteSpese> noteSpeses) {
this.noteSpeses = noteSpeses;
}
#Override
public boolean equals(Object obj) {
try{
VociCosto toCompare = (VociCosto) obj;
if (idCosto==toCompare.getIdCosto()) return true;
return false;
} catch (Exception e){
return false;
}
}
#Override
public int hashCode(){
return idCosto;
}
}
You are doing exacly the opposite of what you are expecting. You should change
#{vociCostoBean.selected.modalita != '1'}
to
#{vociCostoBean.selected.modalita == '1'}
Working test case
View :
<!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>
<h:outputText value="Modalita"></h:outputText>
<p:selectOneMenu value="#{selectMenuActions.value}" immediate="true">
<f:selectItem itemLabel="Importo" itemValue="0"/>
<f:selectItem itemLabel="Quantita" itemValue="1"/>
<p:ajax update="uc" />
</p:selectOneMenu>
<h:outputText value="Costo Unitario"></h:outputText>
<p:inputText id="uc" disabled="#{selectMenuActions.value == '1'}" value="#{vociCostoBean.selected.CUnitario}" />
<br></br>
</h:form>
</h:body>
</html>
Bean :
#ManagedBean
#ViewScoped
public class SelectMenuActions
{
private String m_sValue;
public void setValue(String p_sValue)
{
m_sValue = p_sValue;
}
public String getValue()
{
return m_sValue;
}
}
Related
I have a Java Web 7 project in which I want to write JSF component values directly on an entity instance managed in a backing bean on every p:ajax event. That works fine as long as I add a JSR 303 validation constraint, like #Size(min=5) on one of the entity properties. The value is not longer set on the property with the constraint as long as the constraint is violated. The setter isn't called according to NetBeans debugger; the other property works just fine which leads me to believe that I've isolated the problem. I would like to perform validation when I want and thus get and invalid value set if I want. How to acchieve that?
In my minimal reproducible example I have the entity MyEntity (JPA and JSR 303 annotations)
#Entity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id;
#Size(min = 5)
private String property1;
private String property2;
public MyEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProperty1() {
return property1;
}
public void setProperty1(String property1) {
this.property1 = property1;
}
public String getProperty2() {
return property2;
}
public void setProperty2(String property2) {
this.property2 = property2;
}
}
a JSF page
<?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"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p:inputText value="#{myManagedBean.myEntity.property1}">
<p:ajax/>
</p:inputText>
<p:inputTextarea value="#{myManagedBean.myEntity.property2}">
<p:ajax/>
</p:inputTextarea>
<p:commandButton value="Save">
<p:ajax listener="#{myManagedBean.onSaveButtonClicked}"/>
</p:commandButton>
</h:form>
</h:body>
</html>
and a backing bean
#ManagedBean
#SessionScoped
public class MyManagedBean {
private String value;
private String textAreaValue;
private MyEntity myEntity = new MyEntity();
public MyManagedBean() {
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTextAreaValue() {
return textAreaValue;
}
public MyEntity getMyEntity() {
return myEntity;
}
public void setMyEntity(MyEntity myEntity) {
this.myEntity = myEntity;
}
public void setTextAreaValue(String textAreaValue) {
this.textAreaValue = textAreaValue;
}
public void onSaveButtonClicked(AjaxBehaviorEvent event) {
System.out.println("value: "+value);
System.out.println("textAreaValue: "+textAreaValue);
System.out.println("myEntity: "+myEntity);
}
}
The example can be found at https://github.com/krichter722/jsf-skip-entity-validation. I'm using Primefaces 6.0.
It is working as it is supposed to work. If the validation fails the setter shouldn't be called. If you want you can disable bean validations with this:
<f:validateBean disabled="true"/>
My question is how to get value from selection in 'selectOneMenu' component. I use POJO not String type. I try to display the name property of selected object in inputText. I use commandButton to refresh value in inputText as in code below. But the problem is that nothing appears in inputText. I'm not sure there is need to use converter but I tried and it also hasn't worked.
here is my .jsp file:
<p:selectOneMenu value="#{appointentBean.selectedSpecialization}">
<f:selectItems value="#{appointentBean.specializationResult}" var="i" itemValue="#{i}" itemLabel="#{i.name}"/>
</p:selectOneMenu>
<p:commandButton value="Szukaj" >
<p:ajax update="textid" />
</p:commandButton>
<p:inputText id="textid" value="#{appointentBean.selectedSpecialization.name}" />
appointmentBean:
#ManagedBean
#ViewScoped
#SessionScoped
public class appointentBean
{
private ArrayList<Specialization> specializationResult;
private Specialization selectedSpecialization;
public ArrayList<Specialization> getSpecializationResult()
{
//Here retrievie objects list from database and it works
return specializationResult;
}
public void setSpecializationResult(ArrayList<Specialization> result) {
this.specializationResult = result;
}
public Specialization getSelectedSpecialization() {
return selectedSpecialization;
}
public void setSelectedSpecialization(Specialization selectedSpecialization) {
this.selectedSpecialization = selectedSpecialization;
}
}
Specialization.java:
#Entity
#Table(name="Specializations")
public class Specialization
{
#Id
#GeneratedValue
private int specialization_id;
#Column(name="name")
private String name;
public int getSpecialization_id() {
return specialization_id;
}
public void setSpecialization_id(int specialization_id) {
this.specialization_id = specialization_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
What is more. If I do not make selection on the list NullPointerExcetion appears. But when I make choice i doesn't. So the object is set after selection.
Give a name to your Managed Bean like this
1. #ManagedBean(name ="appointentBean")
2. It should be in Session Scoped or View Scoped not in Both
Your code works perfectly on my End. I did changes to
ArrayList<Specialization> getSpecializationResult() like this:
public ArrayList<Specialization> getSpecializationResult()
{
//Here retrievie objects list from database and it works
specializationResult = new ArrayList<Specialization>();
Specialization specialize= new Specialization();
specialize.setName("Vinayak");
specialize.setSpecialization_id(1);
specializationResult.add(specialize);
return specializationResult;
}
It worked . So, make the necessary changes and let us know.
EDIT 2
Whenever we Deal with POJO's at that time we have to deal with Converter.
Why Custom Converter is the question is what you want to ask now. Refer Custom Converter
These are the steps to create Custom Converter
1. Create a converter class by implementing javax.faces.convert.Converter interface.
2. Override both getAsObject() and getAsString() methods.
3. Assign an unique converter ID with #FacesConverter annotation present in javax.annotation.
First of all I have created a POJOConverter class for your Specialization class
package primefaces1;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
#FacesConverter(forClass=Specialization.class)
public class PojoConverter implements Converter{
public static List<Specialization> specilizationObject;
static {
specilizationObject = new ArrayList<Specialization>();
specilizationObject.add(new Specialization("Vinayak", 10));
specilizationObject.add(new Specialization("Pingale", 9));
}
public Object getAsObject(FacesContext facesContext, UIComponent
component, String submittedValue) {
if (submittedValue.trim().equals("")) {
return null;
} else {
try {
for (Specialization p : specilizationObject) {
if (p.getName().equals(submittedValue)) {
return p;
}
}
} catch(NumberFormatException exception) {
throw new ConverterException(new
FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion
Error", "Not a valid Specialization"));
}
}
return null;
}
public String getAsString(FacesContext facesContext, UIComponent
component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((Specialization) value).getName());
}
}
}
Following changes has been made to your managed Bean class. To overcome the NUll Pointer Exception
package primefaces1;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "appointentBean")
#SessionScoped
public class appointentBean {
private ArrayList<Specialization> specializationResult;
private Specialization selectedSpecialization ;
#PostConstruct
public void init() {
selectedSpecialization = new Specialization();
selectedSpecialization.setName(new String());
selectedSpecialization.setSpecialization_id(0);
}
public appointentBean() {
specializationResult= (ArrayList<Specialization>)
PojoConverter.specilizationObject;
}
public ArrayList<Specialization> getSpecializationResult() {
// Here retrievie objects list from database
//and it works
return specializationResult;
}
public void setSpecializationResult(ArrayList<Specialization> result) {
this.specializationResult = result;
}
public Specialization getSelectedSpecialization() {
if (this.selectedSpecialization != null)
System.out.println("getSelectedSpecialization----"
+ this.selectedSpecialization.getName());
return this.selectedSpecialization;
}
public void setSelectedSpecialization(Specialization
selectedSpecialization) {
this.selectedSpecialization = selectedSpecialization;
}
}
I have made some minute changes to your xhtml for showing values.
<h:body>
<h:form id="me">
<p:selectOneMenu value="#{appointentBean.selectedSpecialization}" >
<f:selectItem itemLabel="Select One" itemValue=""></f:selectItem>
<f:selectItems value="#{appointentBean.specializationResult}"
var="result" itemValue="#{result}" itemLabel="#{result.name}" />
</p:selectOneMenu>
<p:commandButton value="Szukaj" update="me:textid">
</p:commandButton>
<h:outputText value="NAME: "></h:outputText>
<h:outputText id="textid" value="#{appointentBean.selectedSpecialization.name}" rendered="#{not empty appointentBean.selectedSpecialization}"/>
</h:form>
</h:body>
I find myself in the same situation that user2374573, SelectOneMenu, was populated correctly using a custom converter, but the selected item was null. The proposed solution is a variation of the custom converter, but it doesn't solve the problem (at least for me). The value selecting does not arrive as explained in the Primefaces documentation, this occurs because SelectOneMenu operates with String and not with Pojos. After studying In the end I have opted for an intermediate solution.
Instead of having a variable of type pojo to store the value, I use just having a String that stores the id of the element as follows.
This solution has been useful for the SelectOneMenu and also for loading the Targer in the DualList used in the Primefaces Picklist. It is not an ideal solution, but it saves the problem.
Java View
public class PickListView implements Serializable {
private static final long serialVersionUID = 1L;
private List<CviConcesione> listaConcesion;
private CviConcesione concesionSeleccionada;
private String concesionSeleccionadaS;
#Autowired
private ConcesionesBO concesionesBO;
#PostConstruct
public void init() {
}
public List<CviConcesione> getListaConcesion() {
if (null != listaConcesion && !listaConcesion.isEmpty()) {
return listaConcesion;
} else {
listaConcesion = new ArrayList<CviConcesione>();
listaConcesion = concesionesBO.consultaTodasConcesiones();
return listaConcesion;
}
}
public void setListaConcesion(List<CviConcesione> listaConcesion) {
this.listaConcesion = listaConcesion;
}
public ConcesionesBO getConcesionesBO() {
return concesionesBO;
}
public void setConcesionesBO(ConcesionesBO concesionesBO) {
this.concesionesBO = concesionesBO;
}
public CviConcesione getConcesionSeleccionada() {
return concesionSeleccionada;
}
public void setConcesionSeleccionada(CviConcesione concesionSeleccionada) {
this.concesionSeleccionada = concesionSeleccionada;
}
public String getConcesionSeleccionadaS() {
return concesionSeleccionadaS;
}
public void setConcesionSeleccionadaS(String concesionSeleccionadaS) {
this.concesionSeleccionadaS = concesionSeleccionadaS;
}
}
Html Code for select one menu
<p:selectOneMenu
id="concesionR"
value="#{pickListView.concesionSeleccionadaS}"
style="width:125px"
dynamic="true"
converter="#{concesionConverter}">
<f:selectItem itemLabel="Seleccione" itemValue="" />
<f:selectItems value="#{pickListView.listaConcesion}"
var="concesion"
itemLabel="#{concesion.conCodigo} - #{concesion.conDescripcion}"
itemValue="#{concesion.conCodigo}"
ajax = "true"
/>
<p:ajax update="lineaR" process="#form" />
</p:selectOneMenu>
a
Class converter
#FacesConverter("concesionConverter")
public class ConcesionesConverter implements Converter {
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value != null && value.trim().length() > 0) {
try {
PickListView service = (PickListView) fc.getExternalContext().getApplicationMap().get("pickListView");
return service.getListaConcesion().get(Integer.parseInt(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
}
}
else {
return null;
}
}
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null) {
return String.valueOf(((CviConcesione) object).getConId());
}
else {
return null;
}
}
}
This solution does not manage to bring the pojo, but lets you know that it has been selected, showing pojo values.
I'm doing a multiple record editing in primefaces datatable, in the record editing there is file upload, which resets when the user presses the "add" button
The jsf code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form enctype="multipart/form-data">
<p:dataTable var="file" value="#{fileUpload.files}" id="uploadTable">
<p:column>
<p:inputText value="#{file.id}"/>
<p:inputText value="#{file.name}"/>
<p:fileUpload value="#{file.file}" mode="simple"/>
</p:column>
</p:dataTable>
<p:commandButton value="Add" action="#{fileUpload.add}" update="uploadTable" />
<p:commandButton action="#{fileUpload.submit}" value="Submit" ajax="false" />
</h:form>
</h:body>
</ui:composition>
Here's the controller:
#ManagedBean(name = "fileUpload")
#ViewScoped
public class DummyFileUpload implements Serializable {
private static final long serialVersionUID = 1L;
private List<File> files;
#PostConstruct
public void init() {
files = new ArrayList<DummyFileUpload.File>();
}
public void submit() {
// submit
}
public void add() {
files.add(new File());
}
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
public class File implements Serializable{
private static final long serialVersionUID = 2685385696849425824L;
private String id;
private String name;
private UploadedFile file;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
}
}
The file upload control is reset when I do ajax call, I know it's a normal behavior but I'm asking if there's a known workaround for this situation and what could be the best practices for a complex business like this ?
This can be avoided by changing the file upload tag to the following:
<p:fileUpload fileUploadListener="#{fileUpload.add}" mode="advanced" />
This way the Add and Submit buttons as well as the AJAX update are not needed as the advanced version of the file upload will provide the same functionality.
In addition, in your DummyFileUpload bean you wall have to change the add function:
public void add(FileUploadEvent event) {
files.add(event.getFile());
}
I have 2 SelectOneMenu as follows in the index.xhtml. The menu1 essentially chooses a language(sp or en) and menu2 displays the possible serial numbers(0 to 3). I have the init constructor(post constructor) which initialises the default values on the two Menus. However for some strange reason, if I select a serial number other than the default serial number for the language other than the default language, somehow the language gets reset to init default :(
<?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:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>My page</title>
</h:head>
<h:body>
<div>
<h4>Change Existing Description</h4>
</div>
<h:form id="myForm">
<h:panelGrid columns="4">
<h:outputLabel value="Language:" />
<h:selectOneMenu value="#{myBean.language}">
<f:selectItems value="#{myBean.languages}" />
<f:ajax listener="#{myBean.doUpdate}" render ="myForm" />
</h:selectOneMenu>
<h:outputLabel value="SerialID:" />
<h:selectOneMenu value="#{myBean.serialID}">
<f:selectItems value="#{myBean.serialIDs}" />
<f:ajax listener="#{myBean.doUpdate}" render ="myForm" />
</h:selectOneMenu>
</h:panelGrid>
</h:form>
</h:body>
</html>
Here is my Bean code. Where is the problem?? please advise!
package bean;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "myBean")
//#Stateless
#Stateful
#RequestScoped
public class MyBean {
public static final int PERMISSIONS = 2;
private List<String> languages;
private String language;
private int serialID;
private List<Integer> serialIDs;
/**
* init() method for initializing the bean. Is called after constuction.
*/
#PostConstruct
private void init() {
//public MyBean () {
languages = getAllLanguages();
language = "en"; //defaultLanguage
serialID = 3;
serialIDs = getSerialIDsFromOverview();
}
public List<String> getLanguages() {
System.out.println("getLanguages, language " +language);
return languages;
}
public int getPERMISSIONS() {
return PERMISSIONS;
}
public String getLanguage() {
System.out.println("getLanguage " +language);
return language;
}
public void setLanguage(String language) {
System.out.println("setLanguage " +language);
this.language = language;
}
public int getSerialID() {
System.out.println("getSerialID " +serialID);
return serialID;
}
public void setSerialID(int serialID) {
System.out.println("setSerialID " +serialID);
this.serialID = serialID;
}
public List<Integer> getSerialIDs() {
System.out.println("getSerialIDs language = "+language );
return serialIDs;
}
public List<String> getAllLanguages() {
List<String> results = new ArrayList<String>();
results.add("sp");
results.add("en");
if(results != null){
System.out.println("getting all languages");
}
return results;
}
public void doUpdate() {
System.out.println("doUpdate language " +language);
System.out.println("doUpdate serialID " +serialID);
}
/**
* Returns a list of all serialIDs present in the overview.
* #return
*/
private List<Integer> getSerialIDsFromOverview() {
List<Integer> results = new ArrayList<Integer>();
results.add(0);
results.add(1);
results.add(2);
results.add(3);
return results;
}
}
UPDATES:
After taking suggestions from cubbuk, I sat down and corrected my code with #ViewScoped annotation and making the bean implement Serializable. THIS WORKS. However, the next thing I had to do was include an #EJB annotation to call a stateless bean which calls the Entity manager to fetch the serialIDs from a database instead of "hardcoding" it. That is when I encounter the problem: Not serializable exception "java.io.NotSerializableException: bean.__EJB31_Generated__. How do I solve this? When I made myBean back to RequestScope and remove Serializable, I could run the code without problems however there the toggling of the menu to init values :(
By the way I check this post: #EJB in #ViewScoped managed bean causes java.io.NotSerializableException and set my STATE SAVING METHOD to server but that gives me "empy response from server" pop up message :(
Please help!
Since you are using #RequestScoped bean as your backing bean after each request your init method is getting called and your values are getting reset. To avoid that you need to use #ViewScoped bean as your backing bean. I updated your bean accordingly note that your backing bean now implements Serializable interface. This is needed as this bean will be stored in your servlet and it needs to be flushed to disk if the content can not be hold in the memory. For learning the details of #ViewScoped beans please check the following post:
http://balusc.blogspot.com/2010/06/benefits-and-pitfalls-of-viewscoped.html
Apart from these, for naming conventions I renamed your getAllLanguages and getSerialIDsFromOverview methods to initAllLanguages and initSerialIds as methods starting with get and set can be confusing because they are mostly used for getters and setters.
Lastly when you use f:ajax command by default the UIInput the ajax command is bind to is rendered and executed. Since you don't refresh the h:selectOneMenu menus according to the values of each other you don't need to render the whole form. The following will be enough for this case:
<h:form id="myForm">
<h:panelGrid columns="4">
<h:outputLabel value="Language:" />
<h:selectOneMenu value="#{myBean.language}">
<f:selectItems value="#{myBean.languages}" />
<f:ajax listener="#{myBean.doUpdate}"/>
</h:selectOneMenu>
<h:outputLabel value="SerialID:" />
<h:selectOneMenu value="#{myBean.serialID}">
<f:selectItems value="#{myBean.serialIDs}" />
<f:ajax listener="#{myBean.doUpdate}"/>
</h:selectOneMenu>
</h:panelGrid>
</h:form>
#ManagedBean
#ViewScoped
public class MyBean implements Serializable
{
public static final int PERMISSIONS = 2;
private List<String> languages;
private String language;
private int serialID;
private List<Integer> serialIDs;
/**
* init() method for initializing the bean. Is called after constuction.
*/
#PostConstruct
protected void init()
{
//public MyBean () {
System.out.println("lang: " + language);
System.out.println("serialId: " + serialID);
System.out.println("init is called");
initAllLanguages();
initSerialIds();
language = "en"; //defaultLanguage
serialID = 3;
}
public List<String> getLanguages()
{
return languages;
}
public int getPERMISSIONS()
{
return PERMISSIONS;
}
public String getLanguage()
{
return language;
}
public void setLanguage(String language)
{
this.language = language;
}
public int getSerialID()
{
return serialID;
}
public void setSerialID(int serialID)
{
this.serialID = serialID;
}
public List<Integer> getSerialIDs()
{
return serialIDs;
}
private void initAllLanguages()
{
languages = new ArrayList<String>();
languages.add("sp");
languages.add("en");
}
public void doUpdate()
{
System.out.println("doUpdate language " + language);
System.out.println("doUpdate serialID " + serialID);
}
/**
* Returns a list of all serialIDs present in the overview.
*
* #return
*/
private void initSerialIds()
{
serialIDs = new ArrayList<Integer>();
serialIDs.add(0);
serialIDs.add(1);
serialIDs.add(2);
serialIDs.add(3);
}
}
Cheers
Upon deleting an entity from the database I get the following exception:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:101)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:52)
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:767)
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:745)
at org.springframework.orm.hibernate3.HibernateTemplate$25.doInHibernate(HibernateTemplate.java:790)
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:372)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:784)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:780)
at pl.edu.agh.adam.core.projects.dao.TagDAO.delete(TagDAO.java:98)
at pl.edu.agh.adam.core.projects.ProjectService.deleteTag(ProjectService.java:109)
at pl.edu.agh.adam.core.projects.web.TagPresenter.deleteTag(TagPresenter.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIData.broadcast(UIData.java:708)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:890)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:234)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1202)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:623)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:35)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:143)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:93)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
I've dug deep and tried numerous solutions from the hibernate forum, but still I don't know what's going on and where the sessions are opened. The conditions under which this problem occurs:
First: OpenSessionInViewFilter - I've asked about it here. Everything seemed to work fine, but the deleting stopped all of a sudden the following day and all I've done is - I've added a non-connected class to a non-connected package.
<!-- Hibernate OpenSession Filter -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
Second: three-tier architecture. Here are the classes and the JSF page:
#Entity
#Table(name = "tag")
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToMany(mappedBy = "tags", targetEntity = Project.class)
List<Project> projects = new ArrayList<Project>();
#Transient
public static final String PROP_ID = "id";
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "tag_id")
private Long id;
#Transient
public static final String PROP_NAME = "name";
#Column(name = "name", length = 25, unique = true)
private String name;
}
public class TagDAO extends HibernateDaoSupport implements ITagDAO {
#Override
public void create(Tag tag) {
getHibernateTemplate().save(tag);
}
#Override
public Tag getTag(String name){
Tag group = null;
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
criteria.add(Restrictions.eq("name", name));
List<Tag> tags = getHibernateTemplate().findByCriteria(criteria);
if ((tags != null) && (tags.size() > 0)) {
group = (Tag)tags.get(0);
}
return group;
}
#Override
public Tag getTag(Long id){
Tag group = null;
List<Tag> groups = getHibernateTemplate().find(
"from Tag where id = ?", id);
if ((groups != null) && (groups.size() > 0)) {
group = (Tag)groups.get(0);
}
return group;
}
#Override
public List<Tag> getTags(){
List<Tag> ret = getHibernateTemplate().find("from Tag");
System.out.println("Dao got "+ret.size()+" tags");
return ret;
}
#Override
public Integer getTagCount() {
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
criteria.setProjection(Projections.rowCount());
return (Integer)(getHibernateTemplate().findByCriteria(criteria).get(0));
}
#Override
public void delete(Tag group) {
getHibernateTemplate().delete(group);
}
#Override
public void update(Tag group) {
getHibernateTemplate().update(group);
}
#Override
public List<Tag> getTags(Integer first, Integer resultsPerPage,
String order, Boolean asc) {
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
if (asc){
criteria.addOrder(Order.asc(order));
}else{
criteria.addOrder(Order.desc(order));
}
return (List<Tag>)getHibernateTemplate().findByCriteria(criteria, first, resultsPerPage);
}
}
public class ProjectService implements IProjectService {
// Beans used by this service.
private IProjectDAO projectDao;
private ITagDAO tagDao;
#Override
public void createProject(Project project) throws AlreadyExistsException {
if (projectDao.getProject(project.getName()) != null) {
throw new AlreadyExistsException();
}
projectDao.addProject(project);
}
#Override
public List<Project> getProjects(Integer first, Integer howMany, String order,
boolean asc) {
return projectDao.getProjects(first, howMany, order, asc);
}
#Override
public Integer getProjectCount(){
return projectDao.getProjectCount();
}
#Override
public List<Project> getProjects() {
return projectDao.getAllProjects();
}
#Override
public void deleteProject(Long id) {
projectDao.removeProject(id);
}
#Override
public List<Tag> getTags() {
return tagDao.getTags();
}
#Override
public Tag getTag(String name){
return tagDao.getTag(name);
}
#Override
public void createTag(Tag tag) throws AlreadyExistsException {
if (tagDao.getTag(tag.getName()) != null) {
throw new AlreadyExistsException();
}
tagDao.create(tag);
}
#Override
public void deleteTag(Long id) {
tagDao.delete(tagDao.getTag(id));
}
#Override
public void updateTag(Tag tag) {
tagDao.update(tag);
}
}
#ManagedBean(name = "tagPresenter")
#RequestScoped
public class TagPresenter {
private List<Tag> tags;
private IProjectService projectService;
private Tag tag;
public void setTag(Tag tag) {
this.tag= tag;
}
public Tag getTag() {
return tag;
}
public TagPresenter() {
projectService = (IProjectService)ServiceFinder.getInstance()
.findBean("projectService");
tags = projectService.getTags();
}
private void refresh() {
tags = projectService.getTags();
}
public List<Tag> getTags() {
refresh();
return tags;
}
public void deleteTag() {
projectService.deleteTag(tag.getId());
}
}
finally the webpage:
<!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.prime.com.tr/ui">
<ui:composition template="/templates/template.xhtml">
<ui:define name="head">
<title>Tags</title>
<link rel="stylesheet" type="text/css" href="#{facesContext.externalContext.requestContextPath}/styles/style.css"/>
</ui:define>
<ui:define name="content">
<h:form name="commandForm">
<p:dataTable var="tag" name="tagsList" value="${tagPresenter.tags}" paginator="true" rows="10" >
<p:column sortBy="#{tag.id}">
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{tag.id}" />
</p:column>
<p:column sortBy="#{tag.name}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{tag.name}" />
</p:column>
<p:column>
<h:commandLink action="#{tagDisplayer.showTag}" value="Modify">
<f:setPropertyActionListener target="#{tagDisplayer.tag}" value="#{tag}"/>
</h:commandLink>
<h:commandLink action="#{tagPresenter.deleteTag}" value="Delete">
<f:setPropertyActionListener target="#{tagPresenter.tag}" value="#{tag}"/>
</h:commandLink>
</p:column>
</p:dataTable>
</h:form>
<p:messages id="deletingError" showDetail="true"/>
</ui:define>
</ui:composition>
</html>
How is this problem caused and how can I solve it?
Fixes for this vary widely; it can be caused by problems like
bad session handling in your framework configuration
bad cascade settings, incorrect persistence settings
forgetting initialization of an Collection stored in a #ManyToOne database relation.
Make sure to check thoroughly for these cases in your mapping/hibernate configurations - before wasting hours. :D
Take a look at the HibernateTemplate chapter in the Spring documentation. Take a look at implementing a callback approach to access the session.
public void delete(final Tag group) throws Exception {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Object groupObj = session.load(Tag.class, group.getId());
session.delete(groupObj);
return null;
}
};
getHibernateTemplate().execute(callback);
}
If the above is not what you are looking for you can still do a traditional approach as mentioned further down in the Spring documentation. In this approach don't use the HibernateTemplate to delete the object but use the Session from the HibernateDaoSupport to handle the delete.
public void delete(Tag group) throws Exception {
Session session = getSession(false);
Object groupObj = session.load(Tag.class, group.getId());
session.delete(groupObj);
}
This can be caused by calling session.disconnect() instead of session.close().