Writing a stateful (Stateful) session Bean is also very simple, simply by changing the stateless annotation (@Stateless) to a stateful annotation (@Stateful). If you use stateful Sessionbean, the client can save the state when it uses the same Sessionbean object instance, that is, the same Sessionbean object instance that is actually used at the server when the object is referenced multiple times. Stateless Sessionbean uses different instances of the Sessionbean object, and therefore cannot save the state.
An example of a simple shopping cart is written below, which stores the items purchased by the customer in the list object in stateful Sessionbean. These items are then exported using the same Sessionbean object instance on the client. We first implement a Sessionbean remote interface, which is the same as stateless Sessionbean. The code is as follows:
package service;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface ShoppingCart
{
// 添加某个商品信息
public void addCommodity (String value);
// 获得客户购买的所有商品的纱衔泥
public List<String> getCommodity();
}
For convenience, only store names are stored in the list object here, and readers can also save more complex information in the list object, such as using an object to hold the product information.
Here's how to write the specific stateful Sessionbean, the code reads as follows:
package service;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean implements ShoppingCart
{
private List<String> shoppingCart = new ArrayList<String>();
@Override
public void addCommodity(String value)
{
shoppingCart.add(value);
}
@Override
public List<String> getCommodity()
{
return shoppingCart;
}
}