我尝试了一个 EJB 会话 Bean 的示例。我想看看他们的区别。我的基本项目图如下;
http://img109.imageshack.us/img109/8262/85220418.png
项目就像一个购物车。当我通过注入的 EJB 调用托管 bean 以获取添加的 Urun 对象的结果时,结果列表必须是最后一个 Urun 对象。因为我的 EJB 是 @Stateless bean。但是,当我运行应用程序时,它会保留所有新添加的 Urun 对象。但它是无状态的,它必须在每个动作中保留最后一个 Urun 对象。然后,当我在其他网络浏览器中打开应用程序页面时,它会列出之前添加的 Urun 对象列表。但是托管 bean 和 Ejb 在我的模型中是无状态的。但它是一个 Singleton bean。我的问题在哪里?
@Stateless
public class AlisverisSepetiEJB {
List<Urun> urunler=new ArrayList<>();
public List<Urun> getUrunler() {
return urunler;
}
public void setUrunler(List<Urun> urunler) {
this.urunler = urunler;
}
public void urunEkle(Urun urun){
urunler.add(urun);
}
}
@ManagedBean(name="bean")
@RequestScoped
public class JSFYonetimliNesne {
public JSFYonetimliNesne(){
System.out.println("Yönetimli nesne çalıştı");
}
@EJB
AlisverisSepetiEJB alisverisSepeti;
Urun urun=new Urun();
List<Urun> urunler;
public List<Urun> getUrunler() {
return alisverisSepeti.getUrunler();
}
public void setUrunler(List<Urun> urunler) {
this.urunler = urunler;
}
public Urun getUrun() {
return urun;
}
public void setUrun(Urun urun) {
this.urun = urun;
}
public void sepeteKoy(){
alisverisSepeti.urunEkle(urun);
urun=new Urun();
}
}
public class Urun {
String urunAdi;
Long fiyat;
Long gramaj;
public Long getFiyat() {
return fiyat;
}
public void setFiyat(Long fiyat) {
this.fiyat = fiyat;
}
public Long getGramaj() {
return gramaj;
}
public void setGramaj(Long gramaj) {
this.gramaj = gramaj;
}
public String getUrunAdi() {
return urunAdi;
}
public void setUrunAdi(String urunAdi) {
this.urunAdi = urunAdi;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Alışveriş Sepeti</title>
</h:head>
<h:body>
Alışveriş Sepeti
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Ürün adı : "/>
<h:inputText value="#{bean.urun.urunAdi}"/>
<h:outputLabel value="Ürün fiyatı : "/>
<h:inputText value="#{bean.urun.fiyat}"/>
<h:outputLabel value="ÜRün gramajı : "/>
<h:inputText value="#{bean.urun.gramaj}"/>
</h:panelGrid>
<h:commandButton action="#{bean.sepeteKoy}" value="Sepete Ekle"/>
<br><h:outputLabel value="Sepetteki Ürünler"/></br>
<h:dataTable value="#{bean.urunler}" var="item" border="1">
<h:column >
<f:facet name="header">
<h:outputLabel value="Ürün adı"/>
</f:facet>
<h:outputText value="#{item.urunAdi}"/>
</h:column>
<h:column >
<f:facet name="header">
<h:outputLabel value="Ürün fiyatı"/>
</f:facet>
<h:outputText value="#{item.fiyat}"/>
</h:column>
<h:column >
<f:facet name="header">
<h:outputLabel value="Ürün gramajı"/>
</f:facet>
<h:outputText value="#{item.gramaj}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>