8a. Simple shopping cart application using EJB [Stateful Session Bean].

Create EJB File


CartBeanLocal.java

package cart;
import java.util.List;
import javax.ejb.Local;
@Local
public interface CartBeanLocal {
public void initialize(String person) throws Exception;
public void initialize(String person, String id)
throws Exception;
public void addBook(String title);
public void removeBook(String title) throws Exception; public List<String> getContents(); public void remove();
}


CartBean.java ~~~~~~~~~~~~

package cart;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;

@Stateful
public class CartBean implements CartBeanLocal
{
String customerName;
String customerId;
List<String> contents;
public void initialize(String person, String id)
throws Exception {
if (person == null) {
throw new Exception("Null person not allowed."); 
else {
customerName = person;
}
if ( person=="ABC" && id=="123") {
customerId = id;
else {
throw new Exception("Invalid id: " + id);
}
contents = new ArrayList<String>();
}
public void addBook(String title) {
contents.add(title);
}
public void removeBook(String title) throws Exception 
boolean result = contents.remove(title);
if (result == false) 
{
throw new Exception(title + " not in cart.");
}
}
public List<String> getContents() {
return contents;
}
@Remove
public void remove() {
contents = null;
}
}








CartTestServlet.java

package testcart;


import cart.CartBeanLocal;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "CartTestServlet", urlPatterns = {"/CartTestServlet"})
public class CartTestServlet extends HttpServlet {
CartBeanLocal cartBean = lookupCartBeanLocal();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException 
{
response.setContentType("text/html;charset=UTF-8");

try{
cartBean.initialize("ABC", "123");
}
catch(Exception e){}
cartBean.addBook("Java 8 Cookbook");
cartBean.addBook("Enterprise Java 7 ");
cartBean.addBook("Java for Dummies");
cartBean.addBook("Learn Java 8");
try (PrintWriter out = response.getWriter()) {
try{
List<String> books = cartBean.getContents();
for( String s : books)
out.println(s +"<br />");
}catch(Exception e){}
}
}
private CartBeanLocal lookupCartBeanLocal() {
try {
Context c = new InitialContext();
return (CartBeanLocal) c.lookup("java:global/EnterpriseApplication1/EnterpriseApplication1-ejb/CartBean!cart.CartBeanLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}














Comments