Question

I created one session bean and invoke it method in servlet like this:

@WebServlet(name = "NewServlet1", urlPatterns = {"/NewServlet1"})
public class NewServlet1 extends HttpServlet {
@EJB NewSessionBean bean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet NewServlet1</title>");            
        out.println("</head>");
        out.println("<body>");
             out.println("<h2>"+bean.helloWorld()+"</h2>");
        out.println("<h1>Servlet NewServlet1 at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {            
        out.close();
    }
}

And this is my session bean:

@Stateless
public class NewSessionBean {
private int counter = 0;

public NewSessionBean() {
    System.out.println("Constructor works");
}

public String helloWorld(){

return "Hello you are: "+counter++;
}

When I deploy this sources I see in Glassfish that only one instance of session bean was created - 'Constructor works' only once appeared. When I try to refresh my site from several computers I see that only one instance of bean exists. When I create two servlets which use NewSessionBean there is still only one instance. When I read about session beans I understood that there should be pool of beans so it should be several beans. So why there is only one bean created in my example. Help me to understand this situation.

Was it helpful?

Solution

There is only one servlet instance being created and since it generates the response quickly, it does not require additional stateless beans. As noted, if you implement helloWorld as a long operation, and generate a new request before the operation completes, you'll see new beans being created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top