title: Why use session bean at all if ultimately its the HttpSession that holds the state
body: <p>I am new to EJB so please don't mind anything silly in the question.</p>
  
  <p>I have a doubt that someone might be able to solve hopefully. </p>
  
  <p>I have the following Stateful Bean:</p>
  
  <pre><code>@Stateful
  public class SessionBean implements SessionBeanRemote {
  
      private int count = 0;
  
      @Override
      public int getCount(){
      count++;
      return count;
  
      }
  
  }
  </code></pre>
  
  <p>And this is the client that invokes the Bean (Servlet)</p>
  
  <pre><code>@Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          InitialContext ctx;
          HttpSession session = null;
          SessionBeanRemote obj;
          try {
              if (session.getAttribute("myBean") == null) {
                  ctx = new InitialContext();
                  obj = (SessionBeanRemote) ctx.lookup("SessionBean/remote");
                  session.setAttribute("myBean", obj);
              } else {
                  obj = (SessionBeanRemote) session.getAttribute("myBean");
              }
  
              System.out.println(obj.getCount());
  
          } catch (NamingException ex) {
              Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
          }
  
      }
  </code></pre>
  
  <p>Now I was wondering if it is ultimately HttpSession that has to hold the session bean then why use EJB at all, why not just store whatever we want to in the session directly rather than having it in the session bean first and then storing that bean in the session. </p>
  
  <p>And also I was wondering if lets say I change my @Stateful annotation to @Stateless and then execute the same code on the client side and store the bean in the session then also I can extract the same bean from the session then what is the difference between stateless and stateful, I know that when new lookup is done there is a chance that same stateless bean might be returned to me where as with stateful bean it is always new when we do a lookup. But is that it? </p>
  
  <p>P.S. As I mentioned earlier, I am new to EJB and all the doubts are based on what I have understood from a few tutorials online and some questions on SO. I have also tried running it locally but unfortunately I am not able to deploy the application on the GlassFish because of  following error   "Exception while loading the app : EJB Container initialization error". I am trying to look into it. </p>