820 likes | 1.11k Views
Practical Web Application Architectures using IBM WebSphere. Geoff Hambrick IBM WebSphere Enablement Team. This session will include: an overview of IBM WebSphere Standard and Advanced runtime architectures each will be treated separately practical details about the programming model:
E N D
Practical Web Application Architectures using IBM WebSphere Geoff Hambrick IBM WebSphere Enablement Team
This session will include: • an overview of IBM WebSphere Standard and Advanced runtime architectures • each will be treated separately • practical details about the programming model: • components a developer has to program, and how • the kinds of services that are available and how are they used • best practices, from both bottoms up and top down perspectives • discussion of scenarios that you will likely encounter • hands on examples illustrating various "design patterns" useful in developing web applications Introduction
Kasparov • Initial scenarios focused on Web Publishing • world wide access to essentially static information • not much distinction between clients • can get by with read-only non-transactional services Why IBM WebSphere? Internet Client Internet Web Server Client
Rapidly evolving to personalized Web Applications • tie customers, business partners and employees together using the Web • need transactions, persistence and security under program control • drive the need for a Web Application Server to provide these services and necessary infrastructure Why IBM WebSphere? Internet Banking Data Center (CICS, IMS, DB2, Oracle) Bank Customer Extranet Insurance Underwriter Web Application Server Intranet Loan Officer
Web Team 1. Development Phase • Multi-author environment • library system • Multi-disciplinary team • HTML, Java and content • Publishing to web server • IBM WebSphere Studio • Workbench • NetObjects Fusion • ScriptBuilder • VA java Why? IBM WebSphere Provides a Complete End to End Solution Multiple Business Server Platforms (AIX, SUN. NT, MVS...) Data center Existing Apps & DBs (CICS, IMS, DB2, Oracle) Staging Server Development Server 2. Production Phase • Runtime environment • Load balancing • Directory, Security 3. Evaluation Phase • Link checking • Site mapping • Usage patterns • Performance statistics Clustered Production Web App Servers • IBM WebSphere Application Server • Performance Pack • IBM Connector Series • IBM WebSphere Site Analysis Tools Web master
HTTP • Assumes web applications consist of three logical tiers, but IBM WebSphere Standard only includes middle tier components Standard Runtime Architecture: High level view Web Application Server Web Server Back-end Client Web Sphere plug-in • Client • typically is a Web browser that communicates to the Web Server using HTTP • Middle Tier • requests for static pages are handled directly by the WebServer (Standard includes IBM HTTP Server) • dynamic requests are passed to the Web Application Server (in or out process) through the WAS plug-in • Back End • repository of enterprise function and data • communication with client depends on technology
JAVA JAVA HTTP JAVA JAVA • Java representations for each of the three logical tiers: Standard Runtime Architecture: Inside the Web Application Server Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components • Servlet Services • standard Java APIs to handle HTTP requests from client • Application Components • standard artifacts programmed by Web Application developers using Java • Connectors (not included with IBM WebSphere Standard Edition) • Java APIs to handle access to back end resources
JAVA JAVA JAVA JAVA HTTP JAVA JAVA JAVA • Standard artifacts programmed by the developer for the middle tier, roughly one component for each logical tier Standard Runtime Architecture: Web Application Components Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HTTP Servlet Java Server Page Java Bean • HttpServlets • Java programs that control the application flow from page to page • Java Server Pages • extend HTML to alllow fill-in-the blanks from programmatic components • Java Beans (no special support provided by IBM WebSphere Runtime) • provide an extensible contract between other application components
Web Application components: HTTP Servlets • In general, Java servlets are an open standard for executing code on a server: • get all the advantages of Java • easy to code object model • platform independent • are called within the server process • have access to security and transaction context • remain resident once they are loaded for performance • service method handles one or more requests • are themselves stateless • servlets scale across clustered, multiprocessor, multithreaded environments • have access to various Java standard services to maintain state
HTTP Servlets are a standard Java servlet subtype that: • can be found in javax.servlet.http.* package • installed into <IBMWEBAS>/servlets directory • have methods to handle various lifecycle events and HTTP requests • most common are doGet(), doPost(), doPut() • the service() method is overridden when the processing is the same across request type • the init() and destroy() method can be used for one time startup and shutdown logic • can be used to explicitly generate a reply on behalf of the Web Server • HTML, MIME, XML, DHTML • however, are best used to encapsulate conditional application flow logic • leave the presentation logic to Java Server Pages • encapsulate business logic in Java Beans, connectors Web Application components: HTTP Servlets (continued)
2. JAVA JAVA 3. 1. JAVA JAVA HTTP 4. JAVA JAVA JAVA Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HttpServlets: A high-level end-to-end flow HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for an HttpServlet to the Web Server • web server uses its specific mapping rules and determines it should route request to the Web Sphere plug in • plug in activates a Web Application Server (in or out process) • Web Application Server activates HttpServlet with appropriate Servlet Services • Servlet accesses information from servlet services to determine what to do • HttpServlet generates the appropriate HTML reply back to WAS through the Servlet Services based on result • WAS routes reply back to plug in, which passes though to the Web Server specific APIs • Web Server routes reply back to the Browser for handling • action depends on the reply contents
HTTP Servlets: HitCount1 example • Purpose: • shows how an HttpServlet can be used to generate any and all dynamic content • gets values from a number of sources (e.g. instance variables, session state) • shows basic structure of an HttpServlet class • implements service method anda private method to handle CHECKED radio button • however, at this point we don't care too much about the details of the code • graphically illustrates why "monolithic" servlets have development/maintainability problems • HTML is hidden in println statements and cannot be edited with WYSIWYG editors • changing layout requires testing of application flow logic and vice versa
How to run it: • put HitCount1.class in <IBMWEBAS>/servlets directory • URL will be http://<yourWS>/servlet/HitCount1 • try various radio buttons and hit Increment to "count up" and note behaviors in various circumstances • servlet instance variable resets when WAS is brought down and is flaky in concurrent user situations • session state (create if necessary) resets when all browsers on client are stopped or on session timeout • existing session state only will fail first time browser is started or on timeout • sum of active sessions also fails the first time or on timeout, but may show a different count than session if: • there are other clients using HitCount* with the session options • you recycled your browser and "orphaned" a session state value within the timeout period HTTP Servlets: HitCount1 example (continued)
Statistics (a rough estimate of complexity): • number of new components: 1 • source (bytes): 6054 • Things to try: • change the logic, for example: • default to no action (rather than "SRV") • synchronize increment of count to make code thread safe • change the layout: • remove "no cache" calls and check out behavior differences • add session count to sum of active sessions choice • in any case you will have to: • edit the HitCount1.java file (use WordPad) • compile it (javac HitCount1.java) • move HitCount1.class to <IBMWebAS>/servlets HTTP Servlets: HitCount1 example (continued)
What is it: • provides a standard server side scripting language as extensions to HTML • JavaSoft standard (with IBM "template" extensions that are being considered for inclusion) • JSP files are deployed into webserver's HTML directory • WAS plug-in automatically "compiles" them into HttpServlets • best used when the content is mostly static, with some fill-in-the-blanks • can be edited using WYSIWYG tools • should be treated as a "view" component with no control logic • can be used to replace explicitly coded HttpServlets to eliminate compile step, however: • no longer easily edited by a WYSIWYG tool • should be treated as a "controller" component with no display logic Web Application components: Java Server Pages
Most common tags: • set up a JavaBean to be used later using <%=beanname.property%> tags • can be created or not, and scoped to a request, session or user profile • <BEAN name="name in scope" varname="name above" type="class || interface name" • create="yes || no" beanName="class or .ser file name" • introspect="yes || no" scope="request || session || userprofile" > • <param "propertyname"="value to set after instantiation" ... > • </BEAN> • set a value or declare method to be substituted later using <%=variable> tags • <SCRIPT> runat=server> • String variable = code to set the value; • </SCRIPT> • to insert some java code that will directly generate output use <% ... %>, but mainly for: • "controller" JSPs (that call another JSP for layout) • read only data access code • dynamic tables and lists, or tags (like CHECKED or SELECTED) that can onlyappear on one item Web Application components: Java Server Pages (continued)
HTTP Servlet Request JAVA JAVA 1. HTTP Session JAVA JAVA HTTP 4. HTTP Session Context 2. JAVA JAVA JAVA HTTP Servlet Response 3. Java Server Pages: A high level end-to-end flow Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Application Components Servlet Services HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for a JSP to the Web Server • Web Application Server compiles the JSP into an HttpServlet and invokes it • JSP generates HTML reply back to Web Server • Web Server routes reply back to the Browser for handling as before
Java Server Pages: HitCount2a example • Purpose: • shows how to use a JSP in place of an HttpServlet • control logic is embedded in <% %> tags • JSP must now read values from request in <%= %> • illustrates similar problems with monolithic programs • still must test both logic and layout if either one changes • cannot use WYSIWYG tools to edit layout • cannot use IDE tools to edit logic • How to run it: • put HitCount2a.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount2a.jsp • Functionally, there is no difference • However: • no need for an explicit compile step • performance is slower (a lot on first call) • Statistics: • number of new components: 1 • source code (bytes):4307 • difference with HttpServlet is due to elimination of lots of Java syntax
2. JAVA JAVA 1. 3. JAVA JAVA HTTP 5. JAVA JAVA JAVA 4. Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HttpServlets plus Java Server Pages: A high-level end-to-end flow HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for an HttpServlet to the Web Server (as before) • Web Application Server activates HttpServlet with appropriate Servlet Services • Servlet accesses information from servlet services and connectors to determine which JSP to call • HttpServlet activates the appropriate JSP with appropriate services • details to be discussed later • JSP accesses information from servlet services to generate HTML reply back to Web Server • Web Server routes reply back to the Browser for handling as before
HttpServlets plus Java Server Pages: HitCount2 example • Purpose: • shows how a Servlet can be used with JSPs to generate dynamic content • eliminates all the layout code from the servlet • sets string value for count message and source into HttpServletRequest • shows basic structure of a JSP • mostly HTML tags • use of <SCRIPT> tag to implement method to handle CHECKED radio buttons • use of <% %> tag to insert code to prevent caching of result and get attribute values from request • use of <%= %> tags to compute CHECKED attribute on radio buttons and insert count message • graphically illustrates how this MV architecture is easier to develop and maintain • HTML is in a separate file and can be edited with WYSIWYG editors • layout can be is independent of application flow logic and vice versa • however, shows the "looseness" of the contract between the HttpServlet and JSP • need something to document request attribute name/value semantics • not toolable, so cannot use drag and drop tools to generate <% %> and <%= %>
How to run it: • put HitCount2.class in <IBMWEBAS>/servlets directory • put HitCount2.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount2.jsp • starts with an empty page, but then behaves exactly like HitCount1 • Statistics: • number of new components: 2 (HttpServlet, JSP) • source code (bytes):5857 (4643, 1214) • has 97 fewer bytes of total source code than HitCount1 due to elimination of println related logic • Things to try: • change just the logic in HitCount2.java • follow steps from HitCount1 • change just the layout in HitCount2.jsp • simply edit the .jsp in <WebServer>/<HTML> • change the "contract" between them by adding a new variable to display HttpServlets plus Java Server Pages: HitCount2 example (continued)
JavaSoft's "self descriptive, toolable" object standard • provide a means to encapsulate functions and data • tools and programs can query JavaBean about available methods and properties • Java Beans can be "externalized" and "internalized" (serialized) • to and from a .ser file • provides a degree of single instance persistence and configurability • controlled by program in which Bean is instantiated • Typical applications: • Applet Presentation classes (e.g. tables, dialogs) • not discussed here • Common data access classes (e.g. database queries) • will see an example of this later • Contracts between components (e.g. HttpServlets and JSPs) • basically a "pass by value" data structure Web Application components: Java Beans
2. JAVA JAVA 1. 4. 3. JAVA JAVA HTTP 8. 5. JAVA JAVA JAVA 7. 6. Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HttpServlets + JSPs + JavaBeans: A high level end-to-end flow HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for an HttpServlet to the Web Server (as before) • Web Application Server activates HttpServlet with appropriate Servlet Services (as before) • HttpServlet creates and loads a JavaBean with the results • HttpServlet activates the appropriate JSP with a reference to the JavaBean • JSP requests result information from Java Bean • Java Bean returns values back to JSP • JSP generates HTML reply back to Web Server, filling in the blanks with the values requested • Web Server routes reply back to the Browser for handling as before
HttpServlets + JSPs + Java Beans: HitCount3 example • Purpose: • shows how a Servlet can be used with JSPs to generate dynamic content using a JavaBean contract • HttpServlet news up JavaBean, sets its attributes, then adds it into the request attributes • JSP uses <Bean> tag instead of <% %> to get values for <%= %> tags • JavaBean encapsulates attribute values and checked method to handle conditional logic • illustrates need for extensions to JSP • need <NO_CACHE> tag to replace "shotgun" approach • possibly others, like for radio buttons to simplify logic to handle "CHECKED" attribute
How to run it: • put HitCount3.class and HitCountBean.class in <IBMWEBAS>/servlets directory • put HitCount3.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount3.jsp • Statistics: • number of new components: 3 (HttpServlet, JSP, JavaBean) • source code (bytes):6129 (4718, 942, and 469, respectively) • HttpServlet is 75 bytes larger than HitCount2 due to overhead of creating Bean and setting values • JSP is 272 bytes smaller and much less complex due to elimination of: • <SCRIPT> tag to definecheckedmethod (resides in JavaBean) • code to get request attributes (replaced by <Bean> tag) • overall application is 272 bytes larger (coincidentally), however: • the JavaBean source code serves as project documentation (can use javadoc) • can use JavaBean wizards (like those in IBM WebSphere Studio) to code with it • the previous application did not consider this complexity at all... HttpServlets + JSPs + Java Beans: HitCount3 example (continued)
JAVA JAVA JAVA JAVA HTTP JAVA JAVA JAVA Standard Runtime Architecture: Servlet Services • Represents the client tier within the Web Application Server • part of the javax.servlet.http.* package • HttpServletRequest • provides access to URL parameters, session state, and the session context • HttpServletResponse • provides methods to control and generate the reply or invoke other application components • HttpSession • used to maintain user session data between requests (can be clustered) • HttpSessionContext • enables coordination between multiple user sessions Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HTTP Servlet Request HTTP Servlet HTTP Session Java Server Page HTTP Session Context Java Bean HTTP Servlet Response
What is it: • encapsulates WebServer API differences related to getting request data • reference is obtained from service() and do<XXX>() methods • Most commonly used functions: • determine what parameters can be found in the URL (if any) • String[] names = request.getParameterNames(); • parse parameters from the request URL • String[] values = request.getParameterValues("name"); • values is null if the named parameter is not found • get an existing user session associated with this request (if any) • HttpSession session = request.getSession(false); • will only return session state if it already exists • get an existing user session, or create it if necessary • HttpSession session = request.getSession(true); • set new values to pass to "chained" servlets (including Java Server Pages) • this is how request specific JavaBeans are passed to JSPs • ((com.sun.server.http.HttpServiceRequest)request).setAttribute("name", value); • get an attribute passed from a chaining HttpServlet • <Type> value = (<Type>)request.getAttribute("name"); • value is null if attribute does not exist Servlet Services: HttpServletRequest
What is it: • a standard interface to maintain user session (conversational) information • required because HTTP is a "stateless" protocol • data is stored on the server and mapped to user through a session ID • our implementation works with a cluster of Web Application Servers • reference is obtained from either: • the HttpRequest (for the one associated with the request) • the HttpSessionContext (given a specific session id) • trades quality of service for ease of use • cannot count on persistence of session data • can time out • do not use as a "poor man's" database • best to use for easily recomputable values, such as: • login tokens • references to objects that are expensive to obtain • values must be serializable to allow the data to be: • passed among servers in a cluster • cached in and out of memory Servlet Services: HttpSession
Most commonly used functions: • set an application specific value • session.putValue("name", value); • value must be a serializable Object for clustering and persistence to work • get an application specific value set previously • <Type> value = (<Type>)session.getValue("name"); • value is null if the name does not exist in the session • get the session id • often used to provide cross linking between sessions in "collaborative”applications • String sessionId = session.getId(); • get the session context • used to locate other user sessions in collaborative applications • HttpSessionContext context = session.getSessionContext(); • "kill" the session (can trigger HttpSessionBindingListener event) • session.invalidate();// remember: sessions are associated with the user, not an individual HttpServlet • session.removeValue("name");// removes just the values desired, rather thanwhole session Servlet Services: HttpSession (continued)
What is it: • provides a standard interface to coordinate multiple sessions • for example: • on line auctions • multi-player games (checkers, bridge) • same user across multiple machines (or browser instances that don't share cookies) • reference is obtained from an HttpSession • like sessions, using HTTPSessionContext trades off quality of service, especially security, for ease of use • beware of inadvertently affecting other application session data (all is accessible) • probably best to use directory, database or EJB instead Servlet Services: HttpSessionContext
Most commonly used functions • get a specific user session: • HttpSession session = context.getSession("session Id"); • session returned is null if the session id is not found • iterate through the sessions in a context: • Enumeration ids = context.getIds(); • while (ids.hasMoreElements()) { • String id = (String) ids.nextElement(); • HttpSession session = context.getSession(id); • // Operate on the session returned (may be null) • } Servlet Services: HttpSessionContext (continued)
What is it: • encapsulates WebServer API differences related to generating the response to an HTTP request • reference is obtained from service() and do<XXX>() methods • Functions that can be ignored if using MVC architecture: • to write HTML sent to the browser in response to the request • should mainly be used within a Java Server Page, if explicitly at all (see HitCount1 vs. HitCount2) • PrintWriter pw = response.getWriter();// retrieves object into which HTML can be written • pw.print(<HTML string>);or pw.println(<HTML string>); • pw.flush() // optional, to insure block of data is written • to set the header to avoid caching of dynamic pages instead of <Meta> tags • should mainly be used within a Java Server Page • response.setHeader("Pragma", "No-cache"); • response.setHeader("Cache-Control", "no-cache"); • response.setDateHeader("Expires",0); Servlet Services: HttpServletResponse (continued)
Functions needed if using MVC architecture: • to directly invoke a Java Server Page from an HttpServlet(or another JSP) • this is the best performing method for generating HTML from within "read only" HttpServlets • downside is that browser redisplay functions (e.g. back, forward,resize, reload) re-execute servlet when caching is disabled using the above technique • see HitCount2 and HitCount3 for an example • ((com.sun.server.http.HttpServiceResponse)response).callpage( • <JSP URL>, <HttpRequest> • ); • to redirect to another URL • done so that redisplay does not cause update HttpServlets to be executed over and over • response.sendRedirect(<url + query string>); Servlet Services: HttpServletResponse (continued)
2. HTTP Servlet Request JAVA JAVA 5. 3. 1. HTTP Session JAVA JAVA HTTP 4. HTTP Session Context 6. 8. JAVA JAVA JAVA HTTP Servlet Response 7. Servlet-JSP redirect using URL only: A high level end-to-end flow Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Application Components Servlet Services HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for an HttpServlet to the Web Server as before • Web Application Server activates HttpServlet with appropriate Servlet Services as before • HttpServlet invokes a sendRedirect with the JSP after setting attributes into URL • Web Server sends URL redirection for JSP back to Client • Browser receives the redirection and sends an HTTP request for the JSP directly • WAS activates the JSP with attributes in the request • JSP generates HTML reply back to Web Server, filling in the blanks with the values requested • Web Server routes reply back to the Browser for handling as before
Servlet-JSP redirect using URL only: HitCount4 example • Purpose: • shows how to use URL redirection when selected from page • display values must be appended to URL (requires string conversion) • JSP must now read values from request in <%= %> • also shows how cache disabling code can sometimes be eliminated in JSP • we can treat the JSP like a static page once it formats the results • How to run it: • put HitCount4.class in <IBMWEBAS>/servlets directory • put HitCount4.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount4.jsp • Check differences with previous examples • Increment button is the only event that causes a "hit" on the HttpServlet • performance is a little slower when the HttpServlet is hit • however, redisplay is faster unless cache is cleared (no traffic at all!) • even then, the JSP is directly invoked, eliminating the first round trip (flows 1-4) • Statistics: • number of new components: 2 (HttpServlet, JSP) • source code (bytes):5729 (4653, 1076) • comparison with previous example is not as important (different behavior)
Servlet Services 2. HTTP Servlet Request JAVA JAVA 6. 4. 1. HTTP Session 3. JAVA JAVA HTTP HTTP Session Context 5. 7. 8. 11. JAVA JAVA JAVA HTTP Servlet Response 10. 9. Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Application Components Servlet-JSP redirect using JavaBeans: A high level end-to-end flow HTTP Servlet Java Server Page Java Bean • Browser sends HTTP request for an HttpServlet to the Web Server as before • Web Application Server activates HttpServlet with appropriate Servlet Services as before • HttpServlet creates and loads a JavaBean with the results as before • HttpServlet invokes a sendRedirect with the JSP after setting JavaBean into session state • WebServer routes URL for JSP back to Client • Browser intercepts the reply and sends an HTTP request for the JSP directly • WAS activates the JSP with the Java Bean reference in session state • JSP requests result information from the Java Bean • Java Bean returns values back to JSP • JSP generates HTML reply back to Web Server, filling in the blanks with the values requested • Web Server routes reply back to the Browser for handling as before
Servlet-JSP redirect using JavaBeans: Hands on example (HitCount5) • Purpose: • shows how to use URL redirection with a Java Bean • display values must be set into a Bean • Bean must be set into session state • JSP must use Bean tag scoped to session state • shows first example of JavaBean reuse! • HitCount3Bean can be used as is... • How to run it: • put HitCount5.class in <IBMWEBAS>/servlets directory (HitCount3Bean.class should be there already) • put HitCount5.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount5.jsp • select URL redirection and check differences with HitCount4 • URL line on browser has no parameters displayed • use of session state may have performance implications in a cluster under load • when session state expires, "defaults" are displayed if reload is forced • Statistics: • number of new components: 2 (HttpServlet, JSP) • Java Bean doesn't count as it is reused • source code (bytes):5693 (4902, 791)
HTTP Servlet Request JAVA JAVA HTTP Session JAVA JAVA HTTP HTTP Session Context JAVA JAVA JAVA • A variety of Java APIs over connections to back end resources (not included with Standard Edition) Standard Runtime Architecture: Connectors Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components JDBC DB2 UDB HTTP Servlet CICS Java Gateway CICS Java Server Page MQ Connector MQSeries Java Bean ... ... HTTP Servlet Response • Java Data Base Connectivity (JDBC) over UDB • based on a JavaSoft standard • provides for dynamic SQL queries into relational database backed up by DB2 Universal DataBase • Others • in a nutshell, HTTPServlets and JavaBeans are excellent clients anywhere there are Java APIs provided • CICS, MQ, IMS, ComponentBroker, SanFransisco, CORBA ORBs, ... • just make sure to include the appropriate packages in the CLASSPATH (in bootstrap properties)
What is it: • provides a standard interface to execute dynamic relational database queries • is part of javax.sql.* package • the current implementation is based on DB2 Universal Database • can use other databases with appropriate driver Connector APIs: Java Data Base Connectivity
Most commonly used functions: • obtain a connection to the database (consider using connection manager) • use a "class" method (often handled in HttpServletinit() method) • Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); // only need be done once • Connection con = DriverManager.getConnection("database URL");// once per connection • create an object through which to execute one or more SQL statements • Statement stmt = con.createStatement(); • should close() statement when done • execute a command that is not expected to return a result • e.g. "insert" and "update" • do not forget to "commit" changes • stmt.executeQuery("statement"); • execute a query that is expected to return a result • e.g. "select" statements • ResultSet result = stmt.executeQuery("statement"); • while (result.next()) { • <Type> value = (<Type> )result.getObject(<item# in query select clause>); • // Operate on this or other values as desired • } Connector APIs: JDBC (continued)
2. 3. 4. HTTP Servlet Request JAVA JAVA 5. 6. 1. HTTP Session JAVA JAVA HTTP HTTP Session Context JAVA JAVA JAVA Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HttpServlet-JDBC: A high level end-to-end flow JDBC DB2 UDB HTTP Servlet CICS Java Gateway CICS Java Server Page MQ Connector MQSeries Java Bean ... ... HTTP Servlet Response • Web Server makes a request for an HttpServlet as before • Web Application server invokes the HttpServlet as before • HttpServlet directly accesses JDBC using connection and statement object • JDBC implementation sends SQL calls to DB2 UDB • DB2 UDB sends the result back to the JDBC client • JDBC implementation converts the results into Java variables and returns them to the HttpServlet • - ?. HttpServlet uses one of the previous techniques for generating HTML • directly embedded in the HttpServlet code • JSP from request attributes or a bean, using URL redirection or callpage
HttpServlet-JDBC: HitCount6 example • Purpose: • shows how to use JDBC within a Servlet • adds button to JSP • adds code to HTTPServlet (connection made in init method) • everything else is the same as HitCount5 • reuses HitCountBean3 again in redirect call • How to run it: • put HitCount6.class in <IBMWEBAS>/servlets directory • HitCount3Bean.class should be there already • put HitCount6.jsp in <WebServer>/<HTML> directory • must have DB2 UDB 5.0 or better with samples installed • create table HITCOUNT (primaryKey varchar(251) not null primary key, theValue Integer) • URL will be http://<yourWS>/HitCount6.jsp • select database source and check behavior • counts up regardless of whether WAS or Browser recycles • shows error if database goes down • see what happens if you directly modify the database table using DB2 CLP • Statistics: • number of new components: 2 (HttpServlet, JSP) • source code (bytes): 7514 (6630, 884) • comparison with HitCount5 shows an additional 1821 bytes (1728, 93)
2. 5. HTTP Servlet Request JAVA JAVA 6. 1. HTTP Session 3. 8. JAVA JAVA HTTP HTTP Session Context 4. JAVA JAVA JAVA 7. Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components HttpServlet-JDBC though a JavaBean: A high level end-to-end flow JDBC DB2 UDB HTTP Servlet CICS Java Gateway CICS Java Server Page MQ Connector MQSeries Java Bean ... ... HTTP Servlet Response • Web Server makes request to Web Server as before • Web Application server invokes the HttpServlet as before • HttpServlet instantiates JavaBean and invokes access methods • JavaBean accesses JDBC using connection and statement objects as appropriate • JDBC implementation invokes SQL on UDB as before • UDB sends result as before • JDBC converts reply to Java as before (except JavaBean is requestor) • JavaBean returns method result to HTTP Servlet • - ?. HttpServlet generates HTTP response as before
HttpServlet-JDBC through a JavaBean: HitCount7 example • Purpose: • shows how to wrap JDBC calls with a JavaBean • replaces "gorpy" JDBC code in HttpServlet code with "cleaner" JavaBean access • JSP is basically the same (calls HitCount7 instead of HitCount6) • behavior is essentially the same as HitCount6 • reuses HitCountBean3 again • How to run it: • put HitCount7.class and HitCount7Bean.class in <IBMWEBAS>/servletsdirectory • put HitCount7.jsp in <WebServer>/<HTML> directory • DB2 UDB should be set up as per HitCount6 instructions • URL will be http://<yourWS>/HitCount7.jsp • select database source and check that behavior is no differentfrom HitCount6 • use them simultaneously and see what happens • Statistics: • number of new components: 3 (HttpServlet, JSP, JavaBean) • source code (bytes):7653 (5182, 884, 1587) • trading complexity (another bean) for reuse and a simpler,stable HttpServlet • can replace the JDBC access with that to another connector by modifyingthe bean • changes the behavior without changing the servlet • full Model-View-Controller separation!
5. HTTP Servlet Request JAVA JAVA 6. 1. HTTP Session JAVA JAVA HTTP 10. HTTP Session Context 4. 2. 3. JAVA JAVA JAVA 8. 9. 7. Web Application Server Web Server Back-end Client Web Sphere plug-in Connectors Servlet Services Application Components JSP-JDBC though a JavaBean: A high level end-to-end flow JDBC DB2 UDB HTTP Servlet CICS Java Gateway CICS Java Server Page MQ Connector MQSeries Java Bean ... ... HTTP Servlet Response • Web Server makes request to Web Server for a JSP as before • Web Application server invokes the JSP as before • JSP instantiates JavaBean and invokes access methods as part of <%= %> tag • JavaBean accesses JDBC using connection and statement objects as before • JDBC implementation invokes SQL on UDB as before • UDB sends result as before • JDBC converts reply to Java as before (except JavaBean is requestor) • JavaBean returns method result to JSP • JSP generates HTML to return to WebServer • Web Server returns HTTP reply to Client browser as before
JSP-JDBC using a JavaBean: HitCount8 example • Purpose: • shows reuse of a data access JavaBean in a completely new "application" • this one does not test all the features of Standard, and just shows counting the value • also shows how a JSP can be used without ever accessing an HTTPServlet • replaces URL to HttpServlet in FORM action with that of this JSP • How to run it: • HitCount7Bean.class should be in <IBMWEBAS>/servlets directory already • DB2 UDB should be set up from HitCount6 or HitCount7 • put HitCount8.jsp in <WebServer>/<HTML> directory • URL will be http://<yourWS>/HitCount8.jsp • Press increment button and watch count • use it from several clients and HitCount6-7 sequentially and simultaneously to see what happens • Statistics: • number of new components: 1 (JSP) • source code (bytes): 479 (only does one function)
Web Application Architecture • use HttpServlets as as controller code that handles application flow logic • may want to use specialized JSP to eliminate compile step • in any event, no layout code • use Java Server Pages to handle layout logic • may use a JavaBean that directly accesses back end data • however, include no application flow logic • Servlet Services • HTTP request • using a JavaBean to pass more than one attribute value in chained requests • HTTP sessions • use to hold recomputable values rather than application data • minimize the size by storing "keys" to data stored in other sources • choose session state variable names to insure uniqueness across server • take care not to wipe out session data for other applications • best technique is to use (reuse) a single JavaBean named for the HttpServlet • Connectors • wrap calls with a Java Bean • do as much as possible in HttpServlet init method • use connection pooling techniques if not done transparently by connector Some best practices to consider: Programming model perspective
Application Flow (Controller) Operational Environment (Application) Page Layout and Content (View) Business Logic (Model) Page Producer Application Assembler Bean Builder Web Master Concern Some best practices to consider: Development role perspective Role Java Server Pages, HTML, MIME types HTTP Servlets, JavaBeans Configuration Data, Site Usage Statistics Components Produced Java Beans Components Used Java Beans+ others All JavaBeans JavaBeans Programming Skills Required Little or None Pure Java Java + others None WYSIWYG Editors Specialized Wizards Java IDE Tools Admin "Let the right expert do the work."
Analyze business processes to be web enabled • state-transition modelling captures functional requirements • states capture information that is available • transitions capture events, conditions and actions that cause state changes • role analysis captures security requirements • information and transitions accessible by role • easiest if "granularity" is by state • Example "on-line mall" business process: Some best practices to consider: A top down design perspective condition: credit check (order.total cost) is OK action: order.status = confirmed initiate add/delete/change line item submit Entry Shipping Fulfillment final shipment Customer cancel Products Product ID Description Price, shipping, ... Order (status = tentative): Customer: Name, address, etc Method of Payment Line Items: Product ID & quantity Completed purge partial shipment Marketing
Invalid Login Confirm Cancel Login Customer Product Details • Develop Web Application UI Architecture • add "usability" states/transitions to analysis model: • role & task based "home pages" • confirmation and error dialogs • may break large data entry screens into multiple pages • from the client (browser) perspective: • states are HTML "pages" (framesets, forms, tables, ...) • transitions are triggered by URL "links" (buttons, HREFs, ...) • Example Order Entry UI Architecture: Some best practices to consider: A top down design perspective post customer info changes add ok Order Status edit ok invalid back back valid payment show product details cancel login close ok Edit Order invalid payment method submit Confirm Submit back back post product id & quantity next set of products