Eclipse+jboss 5+EJB3 Development Guide (2): Writing stateful Sessionbean

Source: Internet
Author: User
Tags jboss

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;
    }
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.