【发布时间】:2026-01-10 05:15:01
【问题描述】:
我一直在测试我的无状态 ejb:
Java:
@Stateless
@Remote
public class PersonBean {
private String name;
private int reputation;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getReputation(){
return reputation;
}
public void addReputation(){
reputation++;
}
/**
* Default constructor.
*/
public PersonBean() {
// TODO Auto-generated constructor stub
reputation=1;
}
}
和 servlet:
@EJB
PersonBean person;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
person.setName("Mahdi");
String str=person.getName();
person.addReputation();
response.getWriter().write(person.getName()+"
with"+person.getReputation());
}
但是当我调用 servlet 时它返回:null with 1。它应该返回Mahdi with 1。这发生在一个请求中。为什么会这样?
【问题讨论】:
-
两个进程是否在同一个JVM中运行?
-
这不是你的问题的原因,但仅供参考,在这种情况下你可能应该使用有状态的 bean,而不是无状态的
-
@etherous 有状态 bean 工作正常。我的问题是为什么会发生这种情况?
-
“无状态”中不清楚的地方。 “无状态”的意思是“不保持会话状态”。显然,您不应该将状态存储在无状态服务中。
-
每次调用无状态 bean 的方法时,都可能使用不同的 bean 实例。无状态 bean 没有 HTTP 请求范围。他们甚至不知道 HTTP 请求。他们不能保持会话状态。有状态的 bean 是可以做到这一点的 EJB。