下面的 bean 代码来自一个示例项目,属于 JSF 书籍。练习是为了解决以下问题:
当您在第二个浏览器中打开项目时,init()
将再次执行,因为 bean 是会话范围的,因此将生成重复的 DB 条目。提示是使用应用程序范围的 bean 将数据初始化到 DB 中。
我发现了这个问题,但我无法解决。如果我使用@ManagedBean(eager=true)
JSF-Page 将保持为空,并且 DB 似乎没有被初始化。
package hoho;
import java.io.Serializable;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
@ManagedBean
@SessionScoped
public class ComedianHandler implements Serializable {
@PersistenceContext
private EntityManager em;
@Resource
private UserTransaction utx;
private DataModel<Comedian> comedians;
private Comedian currentComedian = new Comedian();
public ComedianHandler() {
Logger.getAnonymousLogger().log(Level.INFO, "Constructor ComedianHandler() called");
}
/*
* Known mistake: method is called per session, i.e. data will be
* written into DB for EACH session
* possible fix: put into application scoped bean
*/
@PostConstruct
public void init() {
Logger.getAnonymousLogger().log(Level.INFO, "'init()' called");
try {
utx.begin();
em.persist(new Comedian("Mario", "Barth", new GregorianCalendar(1972, 10, 1).getTime()));
em.persist(new Comedian("Atze", "Schröder", new GregorianCalendar(1965, 8, 27).getTime()));
em.persist(new Comedian("Dieter", "Nuhr", new GregorianCalendar(1960, 9, 29).getTime()));
em.persist(new Comedian("Anke", "Engelke", new GregorianCalendar(1965, 11, 21).getTime()));
em.persist(new Comedian("Kaya", "Yanar", new GregorianCalendar(1973, 4, 20).getTime()));
comedians = new ListDataModel<Comedian>();
comedians.setWrappedData(em.createNamedQuery("SelectComedians").getResultList());
utx.comwith();
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE, "'init()' did not work", e.getMessage());
}
}
public String save() {
Logger.getAnonymousLogger().log(Level.INFO, "save() [1] with " + currentComedian + "' called");
try {
utx.begin();
currentComedian = em.merge(currentComedian);
Logger.getAnonymousLogger().log(Level.INFO, "save() [2] with " + currentComedian+ "' called");
em.persist(currentComedian);
comedians.setWrappedData(em.createNamedQuery("SelectComedians").getResultList());
utx.comwith();
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE, "'save()' did not work", e.getMessage());
}
return "/display-comedians.xhtml";
}
public String change() {
currentComedian = comedians.getRowData();
Logger.getAnonymousLogger().log(Level.INFO, "change() with " + currentComedian);
return "/comedian.xhtml";
}
public String newEntry() {
currentComedian = new Comedian();
Logger.getAnonymousLogger().log(Level.INFO, "newEntry()");
return "/comedian.xhtml";
}
public String delete() {
currentComedian = comedians.getRowData();
Logger.getAnonymousLogger().log(Level.INFO, "delete() with " + currentComedian);
try {
utx.begin();
currentComedian = em.merge(currentComedian);
em.remove(currentComedian);
comedians.setWrappedData(em.createNamedQuery("SelectComedians").getResultList());
utx.comwith();
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE, "'delete()' did not work", e.getMessage());
}
return null;
}
public DataModel<Comedian> getComedians() {
return comedians;
}
public Comedian getCurrentComedian() {
return currentComedian;
}
public void setCurrentComedian(Comedian currentComedian) {
this.currentComedian = currentComedian;
}
}
小面代码:
<!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">
<head>
<title>Display Comedians</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h:form>
<h:dataTable value="#{comedianHandler.comedians}" var="comedian"
rowClasses="odd,even" headerClass="header" footerClass="footer">
<f:facet name="header">Display all Comedians</f:facet>
<f:facet name="footer">#{resourceBundle.copyright}</f:facet>
<h:column>
<f:facet name="header">First Name</f:facet>
#{comedian.firstName}
</h:column>
<h:column>
<f:facet name="header">Last Name</f:facet>
#{comedian.lastname}
</h:column>
<h:column>
<f:facet name="header">Day of Birth</f:facet>
<h:outputText value="#{comedian.dayOfBirth}">
<f:convertDateTime pattern="dd.MM.yyyy"/>
</h:outputText>
</h:column>
<h:column>
<h:commandButton action="#{comedianHandler.change}" value="Change" />
</h:column>
<h:column>
<h:commandButton action="#{comedianHandler.delete}" value="Delete" />
</h:column>
</h:dataTable>
<h:commandButton action="#{comedianHandler.newEntry}" value="new Entry" style="width: 80px; margin: 10px 2px 2px 2px;" />
</h:form>
</body>
</html>