Java Session Beans



Java Session Beans

Objectives

• Session Bean concepts

• Local and Remote Session Beans

• Stateless and Stateful Session Beans

• Session Bean life cycle

• Accessing Session Beans

Overview

Introduction to Session Beans

Session beans represent a client's interaction with an enterprise application. While servlets and JSP's are meant to be accessed through a web browser, session beans are usually meant to be accessed by other programs or enterprise components. They can be accessed by servlets, other enterprise java beans, or even desktop applications.

Session beans encapsulate business methods and provide an interface for client code. Rather than adding business logic to a client component such as a servlet, the client code needs only to call the business methods of the session bean. This insulates the client from the details of the application's business logic and allows different types of clients to access the same application without having to reproduce or port a large amount of code. It also allows the development process to be split up easily. Web designers can focus on creating a web client for an application while Java programmers can concentrate on setting up the business logic.

A session bean typically represents a single client's interaction with the application and plays the role of the controller in the MVC design pattern. This may be a single method call for simple applications or multiple related calls in a session (such as an online shopping cart). To accommodate the different ways clients interact with applications, session beans come in two varieties: stateful and stateless.

Session beans are very easy to use in the newest version (3.0). The introduction of annotations simplifies session bean creation so that any regular POJO (Plain Old Java Object) can become a session bean. Annotations are metadata that describes a part of an object. They do not directly affect the code itself, but they act as a signal of sorts to other tools or applications that may interact with the object. In this chapter we deal with the annotations used to tell the container that the object is a session bean, which are located in the javax.ejb package.

Container

Like servlets or JSP's which require a container in order to run, session beans require an EJB container. The EJB container provides services like security and transaction management to the enterprise java beans deployed in it. Application servers like Glassfish or JBOSS have containers suitable for running servlets or JSP's in addition to EJB containers. Glassfish is Sun's Java Enterprise Edition application server reference implementation. Like other containers, the EJB container is constantly running, managing lifecycles, allocating resources, and providing services for enterprise beans. The lifecycle of session beans is discussed later in this chapter.

The session beans themselves are just objects and are not, by themselves, executable. They are instantiated by the container and their methods invoked when the container receives a request for them. They are intended to be atomic building blocks for an enterprise application and can often be reused in other applications. So if the session beans are the building blocks and the program is the blueprint, the container is the construction foreman who makes everything happen on time.

Once the application is written, it is deployed to the container. For enterprise applications on Glassfish, this means that the Enterprise Archive (EAR) file is uploaded through the web-based management interface. Once deployed the application has access to the resources that the container provides, including security, resources (like JavaMail sessions, database connection pools, or Java Message Service facilities), and remote management capabilities by means of Java Management Extensions (JMX) with tools like jconsole.

Local and Remote Interfaces

In addition to stateless and stateful varieties, session beans may be defined as local or remote, depending on the requirements of the application. This gives a Java enterprise application the ability to scale if necessary. Unlike servlets which reside in a specific context on a specific server, an enterprise application may span several servers in different physical locations. Local beans are meant to be accessed from within the same container. Remote session beans, as the name implies, may be accessed from remote sources. Remote session beans can be accessed through the Java Naming and Directory Interface (JNDI), a directory service provided by the EJB container. Remote beans can also be accessed locally, so they provide a great deal of flexibility and are a good choice if the application needs to be scalable. The flexibility does come at a price, however, since the JNDI lookups required as well as potentially slow network access can reduce overall performance.

Remote or local access can be defined by the session bean's interface using the @Remote or @Local annotations. The interface, which is a standard Java interface, defines the methods available to clients. By implementing a business interface, the session bean becomes more flexible. The session bean can be modified as needed as long as the interface remains unchanged.

Stateless Session Beans

A stateless session bean is a session bean that does not maintain state information across multiple calls. Each call to the session bean's business methods appears (from the bean's point of view) to come from a different client. It cannot be guaranteed that the stateless session bean object that services the first application request will be the same instance that services future requests. This is because stateless session beans can be pooled by the EJB container. By maintaining a pool of stateless session beans (SSB's), the EJB container is able to conserve resources since it does not have to maintain a unique instance of the SSB for each client.

The life cycle of a stateless session bean is very simple. It either exists or it doesn't. Once has been created it exists in a pool of stateless session beans ready and waiting to service client requests. After it services a request it is placed back into the pool where it patiently awaits another request to service.

Stateless session beans have the advantage of being able to be pooled. Since no state is saved with the session, there is no need to match a specific instance of the bean to a particular client. If subsequent calls are serviced by different instances, the client application does not know (or care). As a result, the total number of session bean instances may be smaller than the total number of clients accessing the application without impacting performance.

Sample Session Bean Interface:

package com.datavikings.sessionbeans;

import javax.ejb.Remote;

@Remote

public interface HelloSessionRemote {

String hiThere(String name);

}

Sample Stateless Session Bean Implementation:

package com.datavikings.sessionbeans;

import javax.ejb.Stateless;

@Stateless

public class HelloSessionBean implements HelloSessionRemote {

public String hiThere(String name) {

return "Hi there, " + name + "!";

}

}

Sample Servlet Client:

package com.datavikings.servlet;

import com.datavikings.sessionbeans.HelloSessionRemote;

import java.io.IOException;

import java.io.PrintWriter;

import javax.ejb.EJB;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

@EJB

HelloSessionRemote greeter;

protected void processRequest(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

if(request.getParameter("name") != null) {

out.println(greeter.hiThere(request.getParameter("name")) + "");

}

out.println("");

out.println("Your name:");

out.println("");

out.println("");

out.close();

}

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

}

As the examples show, a session bean is very similar to a POJO (plain old Java object). The only differences are the annotations, without which the example could easily be a plain servlet application with a helper class. The @Remote annotation in the interface tells the EJB container that the session bean can be accessed remotely with this interface. We could have used @Local, but (as stated previously) the remote interface gives us more flexibility should the application need to scale in the future. The @Stateless annotation in the session bean implementation tells the EJB container that we are not interested in keeping the state of the session bean and that it should not worry about trying to match it with a particular client. The @EJB annotation is a signal that the interface we used is actually an enterprise Java bean and as such will be injected by the EJB container. This is the simplest way to access a session bean, by injecting it into a data member of the client object.

Stateful Session Beans

A stateful session bean keeps its internal state between invocations from the client. It seems pretty obvious, but there are some consequences that must be understood. First, the stateful session beans will be less efficient because the EJB container cannot simply grab the next available session bean and hand it to the client. The client must be matched with the same bean instance that serviced the last request from the client. If no such bean exists, a new one must be created to handle the client (and only that client). As a result, there will be as many stateful session beans as there are clients. Contrast this with the stateless bean, which can be pooled, reducing the total number of instantiated objects and thus conserving memory.

The state that the session bean maintains is the internal state of the object. This should not be confused with the Java Persistence API, which makes data persistent by writing it to a database. If the application is shut down or the server running the EJB container loses power, the session bean ceases to exist. It is not a long-term storage solution. Rather, it is a way to keep track of the conversational state between the application and a client. It is sort of like remembering someone's name for the duration of a phone call rather than writing their name down in your address book to keep permanently.

The life cycle of a stateful session bean is more complicated than its stateless sibling. Because each session bean maintains a specific internal state that corresponds to a particular client session, they cannot be pooled the way stateless session beans can. An analogy of this would be eating dinner at a fancy restaurant. If you ask the waiter for a fork he will bring you one from a “pool” of forks, because they are all pretty much the same. When you get ready to leave however, you expect the valet to bring you the car that belongs to you, not just any car in the lot. Because of this, the stateful session bean must exist for the duration of the client session in case the client needs it again. If the EJB Container decides that it needs to conserve some memory, it may “passivate,” or serialize a stateful session bean and place it in a more long-term storage area in order to free some memory. Before a passivated session bean can service the client the EJB Container must locate it and unserialize it to place it back in memory.

Sample Stateful Session Bean Implementation:

package com.datavikings.sessionbeans;

import javax.ejb.Stateful;

@Stateful(mappedName=”HelloSessionBean”)

public class HelloSessionBean implements HelloSessionRemote {

String name = null;

public String hiThere(String n) {

if(name == null) {

name = n;

return "Hi there, " + name + ". It's nice to meet you";

}

else {

return "Hey, I remember you! Your name is " + name + "!";

}

}

}

Sample Servlet Client:

package com.datavikings.servlet;

import com.datavikings.sessionbeans.HelloSessionRemote;

import java.io.IOException;

import java.io.PrintWriter;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

HelloSessionRemote greeter = null;

try {

InitialContext ctx = new InitialContext();

if(request.getSession().getAttribute("greeter") == null) {

greeter = (HelloSessionRemote) ctx.lookup("HelloSessionBean");

request.getSession().setAttribute("greeter", greeter);

}

else { // Otherwise, get reference from session

greeter = (HelloSessionRemote) request.getSession().getAttribute("greeter");

}

}

catch(NamingException e) {

e.printStackTrace();

}

if(request.getParameter("name") != null) {

out.println(greeter.hiThere(request.getParameter("name")) + "");

}

out.println("");

out.println("Your name:");

out.println("");

out.println("");

out.close();

}

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}

}

The sample stateful session bean is based on the previous example, so it can use the same remote interface as the stateless bean. The session bean used the @Stateful annotation this time, marking it as a stateful session bean. This lets the EJB container know that it must match the client with the same bean instance every time in order to keep the right state information with the right client.

The client servlet needed more code added in order to make the example work in a useful manner. The @EJB annotation that was used in the stateless session bean example was not used for the stateful session bean. The annotation could have been used here as well, but it would have produced an unwanted side-effect. The @EJB annotation is for injecting beans as data members of an object. Because servlets are multi-threaded, every client that accessed the servlet would get the same session bean because the servlet would keep the reference from one invocation to the next. It would make the session bean a little too stateful for what we want. The first client to use the servlet would get a reference to a session bean and every client afterwards would have access to that same instance. Instead of using the annotation the servlet performs a JNDI lookup to locate the bean. The name used in the JNDI lookup matches the name specified with the @Stateful annotation in the session bean implementation. This parameter to the annotation gives the code a way to locate the session bean without having to rely on injection, which would essentially break the way the example servlet is supposed to work.

Practice Labs

Lab 1: Stateless Session Bean Calculator

This lab will demonstrate how to create a simple enterprise application with a web interface. The application is a calculator that will take two numbers and perform mathematical operations on the numbers. Unlike a real calculator which will keep a running total for successive operations, this calculator will simply perform one of four basic arithmetic operations on two numbers and yield a result.

1. Start NetBeans by double-clicking the NetBeans icon.

2. After NetBeans finishes loading, start the New Project Wizard by click ing File -> New Project in the menu bar at the top of the window.

3. In the New Project Wizard, choose Enterprise from the category pane on the left and then choose Enterprise Application from the Projects pane on the right and click the Next button.

4. Choose a name for the project and click the Next button

5. Accept the default values on the final step and click the Finish button

6. Expand the node labeled “SBLab-ejb” in the Project pane on the left

7. Right-click on the Enterprise Beans node under SBLab-ejb and choose “New → Session Bean” from the context menu

8. In the New Session Bean wizard, name the new session bean Calculator. Enter lab.calculator.sessionbeans as the package name. Choose Stateless as the session type and check the Remote interface box. Deselect the Local interface box and click Finish.

9. You will notice that the CalculatorBean.java and CalculatorRemote.java files have been created in the project under the package specified in step 8. To view them, expand the “Source Packages” node under SBLab-ejb and then expand the package (lab.calculator.sessionbeans in this example). The CalculatorRemote.java is the remote interface and the CalculatorBean.java file is the session bean implementation class.

10. Expanding the Enterprise Beans node Under SBLab-ejb in the project pane reveals the newly created session bean. Right-click the session bean and choose Add → Business Method from the menu to open the Business Method wizard.

11. In the Business Method wizard, set the name of the method to “add” and the return type to “double.” Click the Add button to add a parameter to the method named “addend1” and set the type to “double”. Click the Add button again to add a parameter to the method named “addend2” and set the type to “double”. Click OK to create the business method.

12. Expanding the Business Methods node under the CalculatorBean reveals the newly created business method. The method has also been added to the Calculator session bean implementation in CalculatorBean.java and the remote interface defined in CalculatorRemote.java in the lab.calculator.sessionbeans package.

13. Repeat step 11 to create a business method named “subtract” and two parameters of the double type named “minuend” and “subtrahend”. The method should return a double type.

14. Repeat step 11 to create a business method named “multiply” and two parameters of the double type named “factor1” and “factor2”. The method should return a double type.

15. Repeat step 11 to create a business method named “divide” and two parameters of the double type named “dividend” and “divisor”. The method should return a double type.

16. Now that the business methods exist in the session bean, we have to make the methods do something useful. CalculatorBean.java can be found by expanding the lab.calculator.sessionbeans package under the “Source Packages” subnode of SBLab-ejb node in the project. Double-click the file to open it in the editor. Add the following code to the add() business method in CalculatorBean.java in place of the generated return statement so that the method looks like:

public double add(double addend1, double addend2) {

return addend1 + addend2;

}

17. Add the following code to the subtract() business method in CalculatorBean.java in place of the generated return statement so that the method looks like:

public double subtract(double minuend, double subtrahend) {

return minuend - subtrahend;

}

18. Add the following code to the multiply() business method in CalculatorBean.java in place of the generated return statement so that the method looks like:

public double multiply(double factor1, double factor2) {

return factor1 * factor2;

}

19. Add the following code to the multiply() business method in CalculatorBean.java in place of the generated return statement so that the method looks like:

public double divide(double dividend, double divisor) {

return 0.0;

}

When you are finished, the code in CalculatorBean.java should look like this:

package lab.calculator.sessionbeans;

import javax.ejb.Stateless;

@Stateless

public class CalculatorBean implements CalculatorRemote {

public double add(double addend1, double addend2) {

return addend1 + addend2;

}

public double subtract(double minuend, double subtrahend) {

return minuend – subtrahend;

}

public double multiply(double factor1, double factor2) {

return factor1 * factor2;

}

public double divide(double dividend, double divisor) {

return dividend / divisor;

}

}

20. Now that the session bean has been created, expand the SBLab-war node in the project pane on the left, then expand the Web Pages sub-node.

21. Double-click index.jsp to open it in the editor pane.

22. Edit index.jsp so that it contains the following:

Calculator Landing Page

Calculator

Click here to use the Calculator

23. Right-click on the SBLab-war node and choose New → Servlet from the context menu to open the New Servlet wizard.

24. In the New Servlet wizard, name the class Calculator and specify lab.calculator.servlets as the package name. Click Finish to complete the wizard.

25. When the New Servlet wizard is complete, the new servlet will open in the editor pane. Add the code in bold to the processRequest() method so that it looks like:

public class Calculator extends HttpServlet {

@EJB

CalculatorRemote calc;

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

double n1 = 0.0;

if(request.getParameter("n1") != null) {

n1 = Double.parseDouble(request.getParameter("n1"));

}

double n2 = 0.0;

if(request.getParameter("n2") != null) {

n2 = Double.parseDouble(request.getParameter("n2"));

}

out.println("");

out.println("");

out.println("");

out.println("+");

out.println("-");

out.println("*");

out.println("/");

out.println("");

out.println("");

out.println("");

String operation = request.getParameter("op");

String value = "";

if(operation != null && operation.equals("add")) {

value += calc.add(n1, n2);

}

if(operation != null && operation.equals("subtract")) {

value += calc.subtract(n1, n2);

}

if(operation != null && operation.equals("multiply")) {

value += calc.multiply(n1, n2);

}

if(operation != null && operation.equals("divide")) {

value += calc.divide(n1, n2);

}

System.out.println("OPERATION: " + operation + " N1: " + n1 + " N2: " + n2);

out.println("");

out.println("");

} finally {

out.close();

}

}

}

Note that the other generated servlet methods doGet(), doPost(), and getServletInfo() are not shown here as they are not needed in this lab. They are normally hidden in NetBeans by an editor fold – a feature of the editor that collapses auto-generated code to make the display more readable.

26. Save the project

27. Run the project by clicking the Run icon on the tool bar.

Lab 2: Stateful Session Bean Average Tracker

This lab will demonstrate the use of stateful session beans by creating a small enterprise application that allows the user to enter a series of numbers through a servlet. The stateful session bean will keep track of all numbers that a particular user has entered and display the total and average of all numbers entered.

1. Start NetBeans by double-clicking the NetBeans icon.

2. Choose New Project from the File menu.

3. In the New Project Wizard, choose Enterprise from the category pane on the left and then choose Enterprise Application from the Projects pane on the right and click the Next button.

4. Choose a name for the project and click the Next button

5. Accept the default values on the final step and click the Finish button

6. Expand the node labeled “SSBLab-ejb” in the Project pane on the left

7. Right-click on the Enterprise Beans node and choose “New → Session Bean” from the context menu

8. In the New Session Bean wizard, name the new session bean Tracker. Enter lab.tracker.sessionbeans as the package name. Choose Statelful as the session type and check the Remote interface box. Deselect the Local interface box and click Finish.

9. You will notice that the TrackerBean.java and TrackerRemote.java files have been created in the project under the “Source Packages” node and the lab.tracker.sessionbeans subnode. The TrackerRemote.java is the remote interface and the TrackerBean.java file is the session bean implementation class.

10. Open the TrackerBean.java file in the editor window and add the following data members to the class:

private double total = 0;

private int count = 0;

11. Expanding the Enterprise Beans node in the project pane reveals the newly created session bean. Right-click the session bean and choose Add → Business Method from the menu to open the Business Method wizard.

12. In the Business Method wizard, set the name of the method to “add” and the return type to “double.” Click the Add button to add a parameter to the method named “value” of double type. Click OK to create the business method.

13. Expanding the Business Methods node under the TrackerBean reveals the newly created business method. The method has also been added to the Tracker session bean implementation in TrackerBean.java and the remote interface defined in TrackerRemote.java.

14. Repeat step 12 to create a business method named “average” with no parameters. The method should return a double type.

15. Repeat step 12 to create a business method named “getCount” with no parameters. The method should return an int type.

16. Now that the business methods exist in the session bean implementation, add the following code to the add() business method in TrackerBean.java in place of the generated return statement so that the method looks like:

public double add(double value) {

total += value;

count++;

return total

}

17. Add the following code to the average() business method in TrackerBean.java in place of the generated return statement so that the method looks like:

public double average() {

return total / count;

}

18. Add the following code to the getCount() business method in TrackerBean.java in place of the generated return statement so that the method looks like:

public int getCount() {

return count;

}

19. Now that the session bean has been created, expand the SSBLab-war node in the project pane on the left, then expand the Web Pages sub-node.

20. Double-click index.jsp to open it in the editor pane.

21. Edit index.jsp so that it contains the following:

Tracker Landing Page

Tracker

22. Right-click on the SSBLab-war node and choose New → Servlet from the context menu to open the New Servlet wizard.

23. In the New Servlet wizard, name the class Tracker and specify lab.tracker.servlets as the package name. Click Finish to complete the wizard.

24. When the New Servlet wizard is complete, the new servlet will open in the editor pane. Add the following code to the processRequest() method so that it looks like:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

InitialContext ctx = new InitialContext();

TrackerRemote tracker = null;

if(request.getSession().getAttribute("tracker") == null) {

tracker = (TrackerRemote) ctx.lookup("TrackerBean");

request.getSession().setAttribute("tracker", tracker);

}

else {

tracker = (TrackerRemote) request.getSession().getAttribute("tracker");

}

double total = 0;

double average = 0;

int count = 0;

if(request.getParameter("value") != null) {

total = tracker.add(Double.parseDouble(request.getParameter("value")));

}

else {

total = tracker.getTotal();

}

if(tracker.getCount() != 0) {

average = tracker.average();

count = tracker.getCount();

}

out.println("Count: " + count + "");

out.println("Total: " + total + "");

out.println("Average: " + average + "");

RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");

rd.include(request, response);

}

catch(NamingException e) {

e.printStackTrace();

}

finally {

out.close();

}

}

25. Save the project

26. Run the project by clicking the Run icon on the tool bar.

Note: Be sure to deploy the EJB jar file to Glassfish before you run the project. 

Right-click on the EJB project module and choose "Build" from the context menu.  Then highlight the main Enterprise project and run it. 

Summary

In this chapter we examined Session Beans. The purpose of a session bean is to represent a client's interaction with an enterprise application by encapsulating the business logic of an application. Session beans may be defined as local or remote. Local session beans are accessible from within the same JVM instance, whereas remote session beans are accessible across JVM instances, even on different computers. Stateful session beans maintain an internal state that represents a particular client's interaction with an application. Because a stateful session bean is associated with a particular client it cannot benefit from pooling as stateless session beans can. Stateless session beans have a two stage life cycle – they either exist in a pool or do not exist at all. Stateful session beans have a three stage life cycle because they may be passivated, or written to a longer term storage area to free up resources.

Review Questions

1. What software is required for session beans to function?

a. Windows or Linux

b. Java SDK 5 or later

c. An enterprise container such as Glassfish

d. A servlet container such as Tomcat

2. What services can an EJB container provide (choose two)?

a. Life cycle management

b. Security

c. An integrated development environment

d. Pooling for stateful session beans

3. What does a session bean represent?

a. An HTTP session between the client and an application

b. A client's interaction with the enterprise application

c. A resource that can be shared, such as a database

d. An EJB container

4. How can interfaces for session beans can make an enterprise application more flexible?

a. By allowing the session bean to change if needed (as long as the interface stays the same)

b. By separating business logic from the EJB container

c. By allowing developers to concentrate on business logic instead of presentation

d. By hiding the public methods of the class from the client

5. How can session beans can speed up development of an enterprise application?

a. By allowing the session bean to change if needed (as long as the interface stays the same)

b. By separating business logic from the EJB container

c. By allowing developers to concentrate on business logic instead of presentation

d. By hiding the public methods of the class from the client

6. What is the difference between a Local session bean and a Remote session bean?

a. Remote session beans cannot be pooled but local session beans can

b. Local session beans cannot be pooled but remote session beans can

c. Local session beans can only be accessed by client code running in the same JVM

d. Remote session beans are allowed to access network resources

7. What advantage, if any, does a Local session bean have over a Remote session bean?

a. Local session beans can be pooled and thus incur less overhead in the EJB container

b. Local session beans have no advantages over remote session beans

c. Local session beans have fewer stages in their life cycle and thus take up less processing time

d. Local session beans do not require potentially slow JNDI lookups or network access

8. What advantage, if any, does a Remote session bean have over a Local session bean?

a. Remote session beans may be accessed remotely, allow the application to scale

b. Remote session beans have no advantages over local session beans

c. Local session beans have fewer stages in their life cycle and thus take up less processing time

d. Remote session beans to do require potentially slow JNDI lookups or network access

9. Do all session beans have the same lifecycle?

a. Yes, all session beans have the same lifecycle

b. No, remote session beans can be passivated

c. No, stateful session beans can be passivated

d. No, stateless session beans can be passivated

10. What are the two states in a stateless session bean's lifecycle (choose two)?

a. Does not exist

b. Passivated

c. Ready pool

d. Activated

11. Which is NOT a state in a stateful session bean's lifecycle?

a. Does not exist

b. Passivated

c. Ready pool

d. Ready

12. What disadvantages, if any, are involved in using a stateful session bean?

a. There are no disadvantages to using a stateful session bean

b. Stateful session beans cannot be managed by the EJB container

c. A stateful session bean must maintain information about the state of a particular client

d. Stateful session beans cannot be pooled so they require more resources

13. What kind of session bean would be appropriate for the following situation:

A client application in New Delhi requires access to a session bean hosted on an EJB container in New York. The business logic includes some security restrictions and, as a result, must keep track of how many times a particular business method is called. (choose two)

a. Remote

b. Local

c. Stateful

d. Stateless

14. Match the requirement on the left with the appropriate annotation on the right

1. A session bean that can be pooled A. @Local

2. A session bean that keeps state information B. @Remote

3. A session bean interface that can be accessed only on the same JVM C. @Stateless

4. A session bean interface that can be accessed from a different JVM D. @Stateful

15. True or false: it is difficult to implement existing classes as session beans. Why or why not?

Answer Key:

1. C

2. A & B

3. B

4. A

5. C

6. C

7. D

8. A

9. C

10. A & C

11. C

12. D

13. A & C

14. 1 – C

2 – D

3 – A

4 – B

15. False – any plain old Java object (POJO) can be converted into a session bean

Exercises

1. Modify the Lab 1 example to raise and handle an exception when a client requests a division by zero.

2. Modify the Lab 1 example to provide other useful mathematical operations such as square root and exponents.

3. Modify the Lab 1 example to work like a real calculator. The return from any of the business methods should be used as the first operand of future operations (e.g. 1 + 2 = 3 + 4 = 7). Use only stateless session beans.

4. Combine the Lab 1 and Lab 2 to provide a calculator that provides the full functionality of a desktop calculator as well as aggregate functions such as total, average. Add a memory function so that a result can be stored in a stateful session bean and retrieved later like a desktop calculator.

5. Rewrite the Lab 2 example to use the @EJB annotation instead of performing a lookup to access the stateful session bean. Open the application with two different web browsers (e.g. Firefox and Internet Explorer) and try to use them both. What happens?

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download