我正在阅读Java EE 6教程,试图理解无状态会话bean和有状态会话bean之间的区别。如果无状态会话bean在方法调用之间没有保持其状态,为什么我的程序按原样运行?
package mybeans;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
@LocalBean
@Stateless
public class MyBean {
private int number = 0;
public int getNumber() {
return number;
}
public void increment() {
this.number++;
}
}
客户端
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import mybeans.MyBean;
import java.io.PrintWriter;
@WebServlet(name = "ServletClient", urlPatterns = { "/ServletClient" })
public class ServletClient extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
MyBean mybean;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
mybean.increment();
out.println(mybean.getNumber());
}
}
我原本希望getNumber每次都返回0,但它返回1,并且在浏览器中重新加载servlet会使它更多。问题在于我对无状态会话Bean如何工作的理解,而与库或应用程序服务器无关。有人可以给我一个无状态会话bean的简单hello world type示例,当您将其更改为有状态时,其行为会有所不同吗?