840 likes | 1.29k Views
Chapter 8 AJAX Case Study. Chapter 8 Objectives. Integrate various server/client techniques in a comprehensive project Experience the call-back technique and asynchronous programming Practice component based design of Web applications
E N D
Chapter 8 Objectives • Integrate various server/client techniques in a comprehensive project • Experience the call-back technique and asynchronous programming • Practice component based design of Web applications • Develop abilities of making design decisions based on requirements
Introduction • This chapter presents exciting server/client techniques for implementing powerful and user-friendly Ajax Web applications. • Via hands-on experiences with the sophisticated case study project of this chapter, you will have opportunities to practice many technical aspects of Ajax.
Technical Requirements • The following are required for the case study project • NetBeans 6.0.1. • Sun Java System Application Server 9.0 (code name GlassFish2) • Apache JavaDB (included in NetBeans) • To run NetBeans smoothly, you should have at least 1GB memory available.
Background Info of Case Study • “Big Peach” a metropolitan area. • Hundreds of people moving and selling items on yard sale events every day. • Some yard sale hobbyists decide to build a dynamic Web-site for helping yard sale organizers publish information. • Website named “BigPeachYardSaleExpress.com”
Project Requirements • For sellers • Sellers can post information. • Sellers can post the name, price, and thumbnail image of each item for sale. • For buyers • Buyers can search sale events based on date and distance to their home address. • Buyers can visually identify sale events on a map, browse items for sale, and lock/buy items.
Project Requirements Cont’d • For buyers • Depending on shopping cart contents, an itinerary (with driving directions) is generated and can be customized by drag & drop. • User interface requirements • A dynamic advertisement banner will be placed on each page. • The user interface of should be visually appealing.
Technical Solution • A comprehensive Web-site • It consists of the following components • A background database to store sales event information. • A Web application which generates dynamic contents at the server side. • A rich client-side user interface
Database Design • DB schema design is part of high level design • Three database tables in schema • TBL_YARDSALE for storing information of yard sale events (e.g., location and time) • TBL_ITEM for storing items for sale • TBL_TRANSACTION for storing information of buyers
Milestone1: Create Project and DB • Two steps in milestone 1 • Create Project • Create and initialize database • NetBeans and JavaDB are required
Create Project • Create a “Web Application” project • Name it “BigPeachYardSaleExpress” • Make sure to set the following • JavaDB (GlassFish2) • Java EE 5
Create Database • First create a folder for storing SQL scripts • Create an empty text file for SQL Scripts • Enter the SQL Scripts • Run SQL Scripts • SQL Scripts in next slide
SQL Scripts -- 1. Add database user. -- 1.1. Create a user 'bigpeach' with password 'convenience'. CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY( 'derby.user.bigpeach', 'convenience'); -- 1.2. Grant the full access to the 'bigpeach' user. CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY( 'derby.database.fullAccessUsers', SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY('derby.database.fullAccessUsers') || 'derby.user.bigpeach');
SQL Scripts Cont’d -- 2. Drop old tables if there are any. -- NOTE: it removes all OLD data! -- NOTE: it will generate failing messages if the script is executed the 1st time, -- because table does not exist initially! Simply ignore the errors at its 1st run. DROP TABLE tbl_item; DROP TABLE tbl_transaction; DROP TABLE tbl_yardsale;
SQL Scripts Cont’d -- 3. Create the three tables. create table tbl_yardsale( ID VARCHAR(40) PRIMARY KEY, StreetAddr VARCHAR(30), City VARCHAR(20), State CHAR(2), Zipcode VARCHAR(10), FName_Host VARCHAR(20), LName_Host VARCHAR(20), SSN CHAR(10), OpenTime TIME, CloseTime TIME, SaleDate DATE, Description VARCHAR(200) );
SQL Scripts Cont’d create table tbl_transaction( TransactionToken VARCHAR(40) PRIMARY KEY, FName_Buyer VARCHAR(20), LName_Buyer VARCHAR(20), CardNumber VARCHAR(15), TotalAmount decimal(7,2) ); create table tbl_item( ID VARCHAR(40) PRIMARY KEY, SaleID VARCHAR(40), Price decimal(7,2), Description VARCHAR(200), Keywords VARCHAR(30), Image BLOB, Status INT, LastLockTime TIMESTAMP, TransactionToken VARCHAR(40) );
SQL Scripts Cont’d alter table tbl_item add constraint tbl_itemFK FOREIGN KEY (SaleID) REFERENCES tbl_yardsale (ID); alter table tbl_item add constraint tbl_itemFK2 FOREIGN KEY (TransactionToken) REFERENCES tbl_transaction (TransactionToken);
Milestone 2: Portal Page • Objective • Design a page with two links • Learn the use of cascading style sheet • Technique used • Page layout • Page navigation
Page Navigation • Sets the architecture of the whole project • Hands-on steps • Create Page1.jsp • Set the layout to Flow Layout • Add a page fragment (for Ad Banner) • Add two hyperlinks for pointing to seller and buyer pages • Link the hyperlinks to other pages in navigation
Header Layout • Use HTML Table to set up layout • Expected layout as shown in next slide
HTML Table Used <table> <tr> <td width="250px" height="100px" align="center" bgcolor="lightyellow"> <h2>BigPeachYardSaleExpress.COM</h2> </td> <td width="750px" height="100px" align="center" bgcolor="lightblue"> <h2>Dynamic Ads. Here!</h2> </td> </tr> </table>
Refine Layout using CSS • Use HTML Table to set layout of Page1.jsp • Expected layout as shown in next slide
Style Sheet Used .MainTable{ background-color: #ffff01; background-repeat: repeat; border-top-style: ridge; border-bottom-style: ridge; border-left-style: ridge; border-right-style: ridge } .PortalLink{ border-top-style: groove; border-bottom-style: groove; font-size: 18px }
Milestone 3: Seller Page • Objective: • Build seller page • Experience the JavaServerFace (JSF) • Create server side Java files for modeling data tables and manipulating database • Steps: • Create Java files for modeling data tables • Use JSF to build the page
ID Class • Used to represent a unique ID • Each ID is a string, consisting of ten numbers that are connected by dash • The class overrides equals() method. The IDs are regarded as equal when the contents, i.e., ten numbers are exactly the same.
YardSale Class • Used to model TBL_YardSale • Data members correspond to each data column in data table • Persist() function is used to write data into database • Note the use of selfCheck() • Note the use of prepareStatement()
Session Variable Declaration private ID saleID; public void setSaleID(ID id){ saleID = id; } public ID getSaleID(){ return saleID; }
Handling of Submit Button YardSale sale = new YardSale(); try { sale.setValues( (String) this.txtFName.getText(), (String)this.txtLName.getText(), (String)this.txtStreetAddress.getText(), (String) this.txtCity.getText(), (String) this.txtState.getText(), (String) this.txtZip.getText(), (String) this.txtSSN.getText(), (Time) Time.valueOf((String) this.dropDownOpenTime.getValue()), (Time) Time.valueOf((String) this.dropDownCloseTime.getValue()), new Date(this.calendar.getSelectedDate().getTime()), (String) this.txtDescription.getText()); sale.persist(); this.getSessionBean1().setSaleID(sale.getID()); } catch (Exception ex) { ex.printStackTrace(); error(ex.toString()); return null; } return "case1";
Milestone 4: Uploading Items • Objective: • Build a page for uploading items • Learn data table in JSF • Steps: • Create a servlet FetchImage, which given the name and desired size of the image, retrieve the thumbnail image of an item from database • Create a JSF page with data table and then handle all events
FetchImage Servlet • Pay attention to the following methods in the FetchImage class • massageImage() which resets image size • retrieveImage() which reads image from database • processRequest() which processes HTML parameters
MassageImage Method protected byte[] massageImage(byte[] bytesInputImage, int maxWidth){ ByteArrayOutputStream baResult=new ByteArrayOutputStream(); try{ ByteArrayInputStream baInput =new ByteArrayInputStream(bytesInputImage); BufferedImage image = ImageIO.read(baInput); int width = image.getWidth()<maxWidth? image.getWidth() : maxWidth; double ratio = (double) width/image.getWidth(); int height = (int) (ratio *image.getHeight()); BufferedImage bufNewImage = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB); Graphics2D canvas=(Graphics2D )bufNewImage.getGraphics(); canvas.scale(ratio,ratio); canvas.drawImage(image,0,0,new JFrame()); ImageIO.write(bufNewImage, "jpeg", baResult); }catch (Exception ex){ log(ex.toString()); } return baResult.toByteArray(); }
RetrieveImage Method private byte[] retrieveImage(String id, int maxWidth)hrows IOException { Statement sqlStmt=null; Connection cnnDB=null; ResultSet rs=null; byte[] bytesImage=null; //1. get the image. try { cnnDB = Utility.getDBConnection(); sqlStmt = cnnDB.createStatement(); String sqlStr = "SELECT * FROM tbl_item where ID='"+id + "'"; rs=sqlStmt.executeQuery(sqlStr); if (rs.next()) { bytesImage=rs.getBytes("IMAGE"); } else { log("Could not find image with ID" + id); } rs.close(); } //2. massage the image byte [] massagedImage = massageImage(bytesImage, maxWidth); return massagedImage; }