1 / 57

Enterprise Java Servlets

Enterprise Java Servlets. John Ternent Arthur Andersen Business Consulting John.A.Ternent@us.arthurandersen.com. Overview. Introduction Server-based processes Servlet architecture overview J2EE Services overview Database Connectivity - JDBC Messaging Connectivity - JMS

caine
Download Presentation

Enterprise Java Servlets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Enterprise Java Servlets John Ternent Arthur Andersen Business Consulting John.A.Ternent@us.arthurandersen.com (c) 1999, Arthur Andersen, LLP

  2. Overview • Introduction • Server-based processes • Servlet architecture overview • J2EE Services overview • Database Connectivity - JDBC • Messaging Connectivity - JMS • Remote Method Invocation - Java RMI • CORBA Connectivity • Enterprise JavaBeans - EJB • Naming and Directory Services - JNDI • Q&A (c) 1999, Arthur Andersen, LLP

  3. Introduction • What this presentation is NOT: • Power Servlets • Enterprise Servlet Architecture • Tour of J2EE implementation • What this presentation IS: • A starting point for using servlets/JSPs as a gateway into enterprise services (c) 1999, Arthur Andersen, LLP

  4. Server-Side Processes • Brief overview of HTTP • CGI processes • Innovations – ISAPI, NSAPI, Servlets, FastCGI Web Server Files ? ? External Services Business Logic ? Databases (c) 1999, Arthur Andersen, LLP

  5. Server-Side Solutions • ISAPI/NSAPI – Proprietary delegation mechanisms for running logic in-process. • Servlets – Generic, Java-based mechanism for creating business logic. Write Once, Run Anywhere? YES! Apache Netscape IIS Connector Connector Connector Servlet Runner JSDK Servlet Servlet Servlet Servlet (c) 1999, Arthur Andersen, LLP

  6. Servlet Architecture • Common request/response HTTP model • HttpServletRequest • HttpServletResponse • Servlet lifecycle • init() • service() • doGet()/doPost() • destroy() • Security sandbox • Exception handling • A note on JSPs... (c) 1999, Arthur Andersen, LLP

  7. Our First Servlet! import java.io.PrintWriter;import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException { //need to catch ioExceptions here res.setContentType(“text/html”); PrintWriter out = res.getWriter(); out.println(“<HTML><BODY>”); out.println(“<H1>Linux Rocks!</H1>”); out.println(“<H3>Thanks for visiting from” + req.getRemoteAddr() + “!</H3>”); out.println(“</BODY></HTML>”); out.close(); }}

  8. Our First Servlet!

  9. J2EE Services Overview • Database Connectivity - JDBC • Naming & Directory - JNDI • Messaging - JMS • Transaction - JTS • Remote Method Invocation - Java RMI • Enterprise JavaBeans - EJB • CORBA Integration - Java IDL (c) 1999, Arthur Andersen, LLP

  10. JDBC Overview • Architecture • Classes of Interest (all in java.sql): • DriverManager • Connection • Statement • ResultSet • ResultSetMetaData • PreparedStatement • SQLException (c) 1999, Arthur Andersen, LLP

  11. JDBC Architecture Client DriverManager Oracle Driver PointBase Driver ODBC Driver ODBC Source (c) 1999, Arthur Andersen, LLP

  12. JDBC Things-To-Do • Install JDBC provider • JDBC-ODBC provided by default • Oracle • PointBase • Sybase • mySQL • Ensure that JDBC driver is on your system classpath and in your servlet engine’s classpath! (for testing purposes) (c) 1999, Arthur Andersen, LLP

  13. Example 1 – JDBC TestJDBC.java import java.io.*; import java.sql.*; import javax.servlet.http.*; import javax.servlet.*; public class TestJDBC extends HttpServlet { private static Connection conn = null; public void init (ServletConfig conf) throws ServletException { super.init(conf); try { //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName(“oracle.lite.poljdbc.POLJDBCDriver”); conn = DriverManager.getConnection(“jdbc:polite:polite”, “system”, “”); } catch (Exception e) { throw new ServletException (”Error connecting to JDBC"); } }

  14. Example 1 - JDBC TestJDBC.java public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException { try { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<HTML><HEAD><H3>Test JDBC</H3></HEAD><BODY>"); out.println("<TABLE BORDER=1 WIDTH=75%>"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM Table1;"); ResultSetMetaData rsm = rs.getMetaData(); out.println("<TR>"); for (int i = 1; i <= rsm.getColumnCount(); i++) { out.println("<TH>“ + rsm.getColumnName(i) + “</TH>"); } out.println("</TR>");

  15. Example 1 - JDBC TestJDBC.java while (rs.next()) { out.println("<TR>"); for (int i = 1; i <= rsm.getColumnCount();i++) { out.println("<TD>“ + rs.getString(i) + "</TD>“); } out.println("</TR>"); } out.println("</BODY></HTML>"); } catch (SQLException se) { throw new IOException("SQL Exception"); } } }

  16. Example 1 - JDBC

  17. Architecture Classes of Interest (all in javax.jms): Destination Queue* Topic* Sender Receiver Message For Queues and Topics: *ConnectionFactory *Connection *Session JMS Overview (c) 1999, Arthur Andersen, LLP

  18. JMS Architecture Producer Consumer Queue Subscriber Publisher Subscriber Subscriber Subscriber (c) 1999, Arthur Andersen, LLP

  19. JMS Things-To-Do • Install JMS provider • WebLogic includes JMS provider • Java Message Queue available from Sun • Other providers for MQSeries available • Identify JNDI references to factories, queues, and topics you’ll be using. (c) 1999, Arthur Andersen, LLP

  20. Example 2 - JMS TestJMS.html <HTML> <HEAD><TITLE> Your Shopping Cart</TITLE> <H3>Your Shopping Cart</H3><HR></HEAD> <BODY> <FORM ACTION="http://localhost:7001/OrderServlet" METHOD="POST"> <INPUT TYPE=HIDDEN NAME="CustomerNum" VALUE="TER001"> <INPUT TYPE=HIDDEN NAME="OrderNum" VALUE="1207332"> <H4>Order Information for Customer TER001, Order # 1207332</H4><BR> <TABLE> <TR><TH>SKU</TH><TH>Quantity</TH></TR> <TR> <TD><INPUT TYPE="TEXT" NAME="ItemSKU" VALUE="ABC001"></TD> <TD><INPUT TYPE="TEXT" NAME="ItemQty" VALUE="100"></TD> </TR> <TR> <TD><INPUT TYPE="TEXT" NAME="ItemSKU" VALUE="ABC010"></TD> <TD><INPUT TYPE="TEXT" NAME="ItemQty" VALUE="10"></TD> </TR> <TR> <TD><INPUT TYPE="TEXT" NAME="ItemSKU" VALUE="XYZ001"></TD> <TD><INPUT TYPE="TEXT" NAME="ItemQty" VALUE="50"></TD> </TR> <TR> <TD COLSPAN=2 ALIGN="CENTER"><INPUT TYPE="SUBMIT" VALUE="Submit Order"></TD></TR> </TABLE> </FORM> </BODY> </HTML>

  21. Example 2 - JMS OrderServlet.java import java.io.*; import javax.naming.*; import javax.jms.*; import javax.servlet.*; import javax.servlet.http.*; public class OrderServlet extends HttpServlet { public final static String JMS_FACTORY="javax.jms.QueueConnectionFactory"; public final static String QUEUE="javax.jms.exampleQueue"; private static Context ctx; private static QueueConnectionFactory qconFactory; private static QueueConnection qcon; private static QueueSession qsession; private static QueueSender qsender; private static Queue queue;

  22. Example 2 - JMS OrderServlet.java public void init (ServletConfig scfg) throws ServletException { try { ctx = new InitialContext(); qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qcon = qconFactory.createQueueConnection(); qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); try { queue = (Queue) ctx.lookup(QUEUE); } catch (NamingException ne) { // if queue not found try { queue = qsession.createQueue(QUEUE); } catch (Exception e) { throw new ServletException(e.getMessage()); } } ctx.bind(QUEUE, queue); qsender = qsession.createSender(queue); qcon.start(); } catch (Exception e) { throw new ServletException (e.getMessage()); } }

  23. Example 2 - JMS OrderServlet.java public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { String customerNum = request.getParameter("CustomerNum"); String orderNum = request.getParameter("OrderNum"); String[] itemSKUs = request.getParameterValues("ItemSKU"); String[] itemQtys = request.getParameterValues("ItemQty"); TextMessage msg = qsession.createTextMessage(); StringBuffer sb = new StringBuffer("<?XML VERSION=\"1.0\"?>\n"); sb.append("<!DOCTYPE CUSTOMER-ORDER SYSTEM \"http://mycompany.com/order.dtd\">\n"); sb.append("<CUSTOMER-ORDER>\n"); sb.append("<CUSTOMER ID=\"" + customerNum + "\">\n"); sb.append("<ORDER ID=\"" + orderNum + "\">\n"); sb.append("<LINEITEMS>\n"); for (int i = 0; i < itemSKUs.length; i++) { sb.append("<ITEM><SKU>"); sb.append(itemSKUs[i]); sb.append("</SKU>\n<QUANTITY>"); sb.append(itemQtys[i]); sb.append("</QUANTITY>\n</ITEM>\n"); } sb.append("</LINEITEMS>\n</ORDER>\n</CUSTOMER>\n</CUSTOMER-ORDER>"); msg.setText(sb.toString()); qsender.send(msg, DeliveryMode.NON_PERSISTENT, 4, 86400000);

  24. Example 2 - JMS OrderServlet.java response.setContentType("text/html"); response.setHeader("Pragma", "no-cache"); PrintWriter pw = new PrintWriter(response.getOutputStream(),true); pw.println("<HTML><HEAD><TITLE>Order Status</TITLE></HEAD>"); pw.println("<BODY BGCLOR=#FFFFFF><h1>"); pw.println("Order Status</FONT></h1>"); pw.println("Order Submitted: "+ orderNum); pw.println("</BODY></HTML>"); pw.close(); return; } catch (Exception e) {e.printStackTrace(); } } public void destroy () { try { qsender.close(); qsession.close(); qcon.close(); } catch (Exception e) {System.err.println("Error during destroy: " + e.getMessage()); } } }

  25. After the purchase process, users see their shopping cart... Which is processed by our servlet...

  26. A pure XML order is sent to the order fulfillment server... And the servlet reports success back to the user.

  27. Java RMI Overview • Architecture • Classes of Interest: • java.rmi.Remote • java.rmi.server.UnicastRemoteObject • java.rmi.RemoteException • java.rmi.Naming (c) 1999, Arthur Andersen, LLP

  28. Java RMI Architecture Client getName() Implementation return name; User-written Stub Generated Skeleton Java Remote Method Protocol (JRMP)* Naming Service** *As of J2EE, IIOP is also an available RMI protocol ** Many implementations use JNDI as a naming service (c) 1999, Arthur Andersen, LLP

  29. RMI Things-To-Do • Create a remote interface for the module • Write Implementation class • Run rmic compiler on Implementation class • Implement Client • Write Implementation server (registry) • Start naming service (rmiregistry) (c) 1999, Arthur Andersen, LLP

  30. Example 3 - Java RMI Account.java import java.rmi.Remote; import java.rmi.RemoteException; public interface Account extends Remote { public String getName() throws RemoteException; public double getBalance() throws RemoteException; public String getId() throws RemoteException; public void deposit (double amt) throws RemoteException; public void withdraw (double amt) throws RemoteException; }

  31. Example 3 - Java RMI AccountServletClient.java import java.io.IOException; import java.io.PrintWriter; import java.rmi.Naming; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; public class AccountServletClient extends HttpServlet { private static Account myAccount = null; public void init (ServletConfig conf) throws ServletException { super.init(conf); try { myAccount = (Account)Naming.lookup("rmi://localhost/Account1"); } catch (Exception e) { throw new ServletException ("Could not connect to Account RMI Server"); } }

  32. Example 3 - Java RMI AccountServletClient.java public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException { try { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<HTML><HEAD><H3>Account Information for "); out.println(myAccount.getName()); out.println(", account number "); out.println(myAccount.getId()); out.println("<HR></HEAD><BODY>"); out.println("<H3>Current balance : " ); out.println(myAccount.getBalance()); out.println("</H3><P><H3>Depositing $500 ... </H3></P>"); myAccount.deposit(500); out.println("<P><H3>New balance"); out.println(myAccount.getBalance()); out.println("</H3></P></BODY></HTML>"); } catch(Exception e) { System.err.println("Error in AccountClient "+e); } } }

  33. Example 3 - Java RMI

  34. CORBA Overview • Architecture • Classes of Interest: • org.omg.ORB • Helpers • Holders • NamingContext (COSNaming) (c) 1999, Arthur Andersen, LLP

  35. CORBA Architecture Client (Java) getName() Implementation return name; (C++) Interface Definition (IDL) Stub Skeleton Object Request Broker (ORB) -- IIOP Security Trader CosNaming CORBAServices Licensing Persistence (c) 1999, Arthur Andersen, LLP

  36. CORBA Things-To-Do • Create an IDL interface for the module • Acquire idltojava compiler (presently a separate download from Sun) • Run idltojava compiler on IDL interface • Implement Client • Examples use JavaIDL -- mileage can (and will) vary by vendor (Inprise/Iona). (c) 1999, Arthur Andersen, LLP

  37. Example 4 - CORBA BankingInterface.idl module BankingInterface { interface AccountManager { struct AccountData { string fullName; string accountId; double balance; }; typedef sequence<AccountData> AccountDataSet; exception InvalidAccountException {}; exception NameNotFoundException {}; AccountData getAccountByID (in string accountId) raises (InvalidAccountException); AccountDataSet getAccountByLName (in string name) raises (NameNotFoundException); }; };

  38. Example 4 - CORBA AccountClient.java public class AccountClient extends HttpServlet{ private static ORB orb = null;private static NamingContext nctx = null; public void init (ServletConfig conf) throws ServletException { super.init(conf); String[] args = {"-ORBInitialPort" , "1050"}; try { orb = ORB.init(args, null) ; org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService"); nctx= NamingContextHelper.narrow(nameServiceObj); System.out.println ("Resolved names..."); NameComponent nc = new NameComponent("AccountManager", ""); NameComponent[] path = {nc}; am = AccountManagerHelper.narrow(nctx.resolve(path));} catch (Exception e) { // Write any problems to the servlet log e.printStackTrace(System.err);} }

  39. Example 4 - CORBA AccountClient.java public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException { try { PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.println("<HTML><HEAD><H3>Account Information for "); String lname = req.getParameter("lname"); String accountCode = req.getParameter("code"); out.flush(); Vector accounts = new Vector(); if (lname == null) { out.println("account "); out.println(accountCode); AccountData ad = am.getAccountByID(accountCode); accounts.addElement(ad); }

  40. Example 4 - CORBA AccountClient.java else{ out.println ("names starting with "); out.println (lname); AccountData[] ad = am.getAccountByLName(lname); for (int i = 0; i < ad.length; i++) { accounts.addElement(ad[i]); } } out.println("</HEAD><BODY>"); out.println(writeAccountInfo(accounts)); out.println("</BODY></HTML>"); } catch(org.omg.CORBA.SystemException e) { System.err.println("CORBA Error in AccountClient <init>"+e); } catch(Exception e) { System.err.println("Error in AccountClient <init>"+e);} }

  41. Example 4 - CORBA AccountClient.java private String writeAccountInfo(Collection ad){ StringBuffer sb = new StringBuffer("<TABLE BORDER=1>"); java.util.Iterator it = ad.iterator(); while (it.hasNext()){ AccountData a = (AccountData) it.next(); sb.append("<TR><TD>"); sb.append(a.fullName); sb.append("</TD><TD>"); sb.append(a.accountId); sb.append("</TD><TD>"); sb.append(a.balance); sb.append("</TD></TR>"); } sb.append("</TABLE>"); return sb.toString(); } private AccountManager am = null; }

  42. Example 4 - CORBA

  43. EJB Overview • Architecture • Classes of Interest: • EJBHome • Remote • SessionBean • EntityBean (c) 1999, Arthur Andersen, LLP

  44. EJB Architecture EJB Server EJB Container Client Home Bean Remote (c) 1999, Arthur Andersen, LLP

  45. EJB Things-To-Do • Get an EJB Server • J2EE • WebLogic • GemStone • Inprise • Identify Home and Remote Interfaces for target classes. • Deploy servlet into J2EE server context • Usually with a custom deployer tool provided by server vendor. • May be deployed in a Web ARchive (WAR) file (c) 1999, Arthur Andersen, LLP

  46. Example 5 - EJB TestAccountServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.rmi.PortableRemoteObject; import java.rmi.RemoteException; import javax.naming.InitialContext; import Account; import AccountHome; public class TestAccountServlet extends HttpServlet { Account account; public void init() throws ServletException { try { InitialContext ic = new InitialContext(); Object objref = ic.lookup("Account"); AccountHome home = (AccountHome)PortableRemoteObject.narrow(objref, AccountHome.class); account = home.create("123456", "John Smith", 1000.00); } catch(Exception e) { e.printStackTrace(); } }

  47. Example 5 - EJB TestAccountServlet.java public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { String inputString = req.getParameter("inputString"); Integer inputNumber = new Integer(inputString); account.deposit(inputNumber.intValue()); double balance = account.getBalance(); res.setContentType("text/html"); PrintWriter out = res.getWriter(); generatePage(out,balance); } catch (Exception e) { throw new ServletException(e.getMessage()); } } public String getServletInfo() { return "This servlet accesses an enterprise bean."; }

  48. Example 5 - EJB TestAccountServlet.java private void generatePage(PrintWriter out, double balance) throws RemoteException { out.println("<html>"); out.println("<head>"); out.println("<title>Input for AccountServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("The current balance for "); out.println(account.getName()); out.println("'s account is: "); out.println(String.valueOf(balance)); out.println("<p>"); out.println("<form method = get action=\"AccountManager\">"); out.println("Please enter an integer:"); out.println("<input type=text name=\"inputString\">"); out.println("<p>"); out.println("<input type=submit>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } }

  49. JNDI Overview • Wrapper around LDAP, NDS, ADS, CosNaming, and other naming/directory services • Classes of Interest: • InitialContext • InitialDirContext • SearchResults (c) 1999, Arthur Andersen, LLP

More Related