Fri Oct 10, 2008 12:27 am
package ejb_stateful;
import java.util.Collection;
import javax.ejb.Remote;
@Remote
public interface Cart {
public void addItem(String item);
public void removeItem(String item);
public Collection getItems();
}
import java.util.ArrayList;
import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
@Stateful
public class CartBean implements Cart {
private ArrayList items;
@PostConstruct
public void initialize() {
items = new ArrayList();
}
public void addItem(String item) {
items.add(item);
}
public void removeItem(String item) {
items.remove(item);
}
public Collection getItems() {
return items;
}
}
package ejb_stateful;
import java.util.Collection;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class CartClient {
public static void main(String [] args) throws NamingException {
try {
final Context context = getInitialContext();
Cart cart = (Cart)context.lookup("CartBean");
System.out.println("Adding items to cart");
cart.addItem("Pizza");
cart.addItem("Pasta");
cart.addItem("Noodles");
cart.addItem("Bread");
cart.addItem("Butter");
System.out.println("Listing cart contents");
Collection items = cart.getItems();
for (Iterator i = items.iterator(); i.hasNext();) {
String item = (String) i.next();
System.out.println(" " + item);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static Context getInitialContext() throws NamingException {
return new InitialContext();
}
}
Adding items to cart
Listing cart contents
Pizza
Pasta
Noodles
Bread
Butter
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.