import java.io.*; import javax.servlet.http.*; import javax.servlet.*; import javax.rmi.*; import javax.naming.*; import java.util.*; public class ClientViewServlet extends HttpServlet { /* This servlet interacts with the Client Entity EJB. The client EJB has a finder method, findBySalesman. This method accepts the salesman id and obtains all the clients whom this salesman is supposed to visit. */ ClientHome clientHome; public void init() throws ServletException { try { System.out.println("trying to get initial context"); Context ic = (InitialContext) getInitialContext(); System.out.println("Got InitContext"); Object objRef = ic.lookup("Client"); System.out.println("Got obj ref"); clientHome = (ClientHome) PortableRemoteObject.narrow(objRef,ClientHome.class); System.out.println("Got Home"); }catch(Exception e) { System.out.println("Error in init"); e.printStackTrace(); } } public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { try { HttpSession session = req.getSession(false); //obtain the salesman id from the session. String strSalesmanId = (String)session.getAttribute("SalesmanId"); /* Use the salesman id to search for clients that the salesman is supposed to visit. */ Collection clients = clientHome.findBySalesman(strSalesmanId); if(clients.size() <= 0) //No clients found { res.sendRedirect(res.encodeURL("/Status.jsp?code=4")); } /* Create an array of Vector objects. Each Vector object stores the Client id - first position in Vector Client Name - second position in Vector Client Address - third position in Vector It then stores this array of Vectors in the session */ Vector cinfo[] = new Vector[clients.size()]; Iterator i = clients.iterator(); int cnt=0; while(i.hasNext()) { Client client = (Client) i.next(); cinfo[cnt] = new Vector(3); cinfo[cnt].add(client.getId()); cinfo[cnt].add(client.getName()); cinfo[cnt].add(client.getAddress()); cnt++; } //Store the array of vectors in the session. Each Vector represents one client. session.setAttribute("ClientList",cinfo); //send redirection to ClientListJSP. res.sendRedirect(res.encodeURL("/ClientList.jsp")); }catch(Exception e){ System.out.println("Error while obtaining client list:" + e.getMessage()); res.sendRedirect(res.encodeURL("/Status.jsp?code=1")); } } private Context getInitialContext() throws NamingException { Context initial = null; try { /* There are other methods of obtaining the initial context too. Check the J2EE docs and your application server docs for these. */ initial = new InitialContext(); }catch(Exception ne) { System.out.println("Unable to get an initial context"); } return initial; } }