我正在尝试为单个会话bean提供一个基本模板。然后,我以“柜台的体系结构”中包含的示例为例:
https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples002.htm
但是,在运行示例时,我无法打印count.hitCount的值。
我发现访问变量时没有getter的常见问题。例如,在index.html中:
<ui:define name="title">
This page has been accessed #{count.hitCount} time(s).
</ui:define>
但是,在Count.java中包括getter getHitCount():
@Named
@SessionScoped
public class Count implements Serializable {
@EJB
private CounterBean counterBean;
private int hitCount;
public Count() {
this.hitCount = 0;
}
public int getHitCount() {
hitCount = counterBean.getHits();
return hitCount;
}
public void setHitCount(int newHits) {
this.hitCount = newHits;
}
最后,CounterBean.java增加变量:
@Singleton
public class CounterBean {
private int hits = 1;
// Increment and return the number of hits
public int getHits() {
return hits++;
}
}
感谢您的帮助和评论,我们非常感谢。
最佳答案
具有显示时间的计数器的facelet:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
This page displayed #{counterController.hitCount} times.
</h:body>
</html>
CounterController
是一个@RequestScoped
bean,用于通过其CounterBean.hitCount
方法增加@PostConstruct
:package x;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
@Named( value = "counterController" )
@RequestScoped
public class counterController
{
@EJB
private CounterBean counterBean;
@PostConstruct
public void initialize()
{
counterBean.incHitCount();
}
public int getHitCount()
{
return counterBean.getHitCount();
}
public CounterController()
{
}
}
CounterBean
是用于存储hitCount的@Singleton
EJB。 @StartUp
批注将其构造为一个热切构造的bean(在启动任何客户端请求之前在应用程序启动时创建):package x;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import lombok.Data;
@Singleton
@Startup
public class CounterBean
{
private int hitCount;
public int getHitCount()
{
return hitCount;
}
public void incHitCount()
{
hitCount++;
}
public CounterBean()
{}
}