i'm new in JavaEE and I try to figure out the difference between stateless and stateful session beans. What I have understood so far:
1.) in stateful session beans the state of the bean is bound with the client; therefore as long as we are in the same session with the same user there should be the same state of the bean instance
2.) in stateless session beans there is no state bound to the session and the client; in fact, the bean instances can interchange on every invocation or request of the user
To try this I wrote a short servlet which just print out the number of hits with every request on a stateless bean. This is the servlet:
package com.java.ee.ejb.stateless;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet
public class StateLessServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private StateLessBean stateLessBean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(stateLessBean);
stateLessBean.increaseHits();
resp.getWriter().write("<h1>Hits: "+stateLessBean.getHits()+"<h1>");
}
}
And this is the stateless bean:
package com.java.ee.ejb.stateless;
import javax.ejb.Stateless;
@Stateless
public class StateLessBean {
private int hits;
public void increaseHits() {
hits++;
}
public int getHits() {
return hits;
}
}
But it seems to be, that I invoked the methods every time on the same object - should it not be exact the opposite, that means invocation each time on different instances when I use stateless session beans? Have I forgot something?
increaseHits()
method, and you'll start seeing differences. – JB Nizetthis.toString()
in the EJB methods. – JB Nizet