Creating the Web page, servlets, and JSP files

To construct the components of project SV001585:

  1. Create a web project.
  2. Write a shop.html page with Page Designer containing a link that invokes a GetItems servlet
  3. Import the jt400.jar file for the iSeries Toolbox for Java classes into the Web project lib folder. You can find this jar file in x:\wdsc\wssd\plugins\com.ibm.etools.iseries.toolbox\runtime where x is the directory in which you installed Development Studio Client.
    Note:
    See GetItems.java and ViewItems.jsp in the SV001585 project to see the main iSeries Toolbox for Java JDBC and SQL related parts, for the servlet and JSP. In the Navigator view of the Web perspective, you can find GetItems.java by expanding SV001585 > source, and you can find ViewItems.jsp by expanding SV001585 > webApplication.
    .
  4. Write a GetItems servlet that uses the iSeries Toolbox for Java JDBC and SQL to retrieve clothing items from the iSeriesINVENTORY database that:
    1. Places the ResultSet bean containing the SQL query result on the session
    2. Redirects the request to ViewItems.jsp

    Code sample for GetItems.jsp:

    public void init() {
    			.
    			.
    			.
    			// Load the IBM Toolbox for Java JDBC driver.
    			DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
    			// Note that we have retrieved the as400 name, userid, and password from 
    			// web.xml file using and xml parser.
    			as400conn =
    				DriverManager.getConnection(
    					"jdbc:as400://" + as400 + ";naming=sql;errors=full",
    					userid,
    					password);
     
    			dmd = as400conn.getMetaData();
    			.
    			.
    			.
    }
     
    public void service(HttpServletRequest request, HttpServletResponse response){
    			.
    			.
    			.
    			Statement select =
    				as400conn.createStatement(
    					ResultSet.TYPE_SCROLL_INSENSITIVE,
    					ResultSet.CONCUR_READ_ONLY);
    			ResultSet rs =
    				select.executeQuery(
    					"SELECT PRODNO, PRODNAME, RPRICE, IMAGE FROM "
    						+ retailLibrary
    						+ dmd.getCatalogSeparator()
    						+ inventoryFile);
     
    			HttpSession session = request.getSession(true);
    			session.setAttribute("resultset", rs);
     
    			response.sendRedirect("/ViewItems.jsp");
     
    			.
    			.
    			.
    }
     
    
  5. Write a ViewItems JSP file that retrieves the clothing items from the ResultSet bean obtained in the previous step, to display the clothing items in a table format. The JSP file should also include a form for each item that you can use to select size and quantity, and then add the item to your basket. You can use Page Designer in iSeries Web development tools to write the JSP. More specifically, you can lay out the page in the Design view, and add appropriate code in the Source view. Code sample for ViewItems.jsp:
    <!--Getting the ResultSet Object from the session--><%
       int columnCount = 0;
       ResultSet rs = (ResultSet)session.getAttribute("resultset");
       if(rs !=null)
    %>   
    <%
      {
      rs.beforeFirst();
                ResultSetMetaData rsmd = rs.getMetaData ();
                columnCount = rsmd.getColumnCount ();
                
    %>
    <TABLE border="1">
    <TBODY>
    <TR>
    		<TD>Product ID</TD>
    		<TD>Name</TD>
    		<TD width="551">Price</TD>
    		<TD colspan="2"></TD>
    </TR>
    <%while (rs.next ()){
    <TR>
    <!--Creating a form for this row (or this item)-->
    <FORM name="myform" action="/SV001585/AddtoBasket" 
    onsubmit="return errorChecking(this);">
     
    <!--Getting each column data from this row of ResultSet object-->	
    <!--Process data is a user defined method to modify the data for 
    display if needed-->	
          	   <%	
                    for (int i = 1; i <= columnCount; ++i){         
                        String value = rs.getString(i);	            
                        if (rs.wasNull ())
                            value = "<null>"; 
                        else{
                        	if(i==1)
                        		prodID=value;	
                        	value = processData(i,value);
                        	
                    	  }	    
    			  %>
    				<TD><%=value%></TD>
    				  <%            
                    } 
    			%>
     
    <!--Creating quantity input field and size drop down menue-->
    <!--Note that we are using product id as the name of the field-->
             <TD width="290">Quantity 
    			<INPUT size="5" type="text" name='<%=prodID+"Q"%>' ><BR>
    					Size <SELECT name='<%=prodID+"S"%>'>
    							<OPTION value="s" selected>Small</OPTION>
    							<OPTION value="m" selected>Medium</OPTION>
    							<OPTION value="l" selected>Large</OPTION>
    							<OPTION value="XL" selected>Extra Large</OPTION>
    							<OPTION value="XXL" selected>Extra Extra Large</OPTION>
    							</SELECT>
    </TD>
    <TD><INPUT type="image"   name="submit"  
    src="images/Add_to_basket.gif"></TD>
    </FORM>
    </TR>
    <%
    }
    %>
    </TBODY>
    </TABLE>
    <%
    }
    
  6. Import the iSeries Java development tools iseriesut.jar file into the lib folder for your your Web project. You can find this JAR file in x:\wdsc\wssd\plugins\com.ibm.etools.iseries.toolbox\runtime, where x is the directory in which you installed the product. See AddtoBasket.java and ViewBasket.jsp in the SV001585 project to see the implementation. In the Navigator view of the Web perspective, you can find AddtoBasket.java by expanding SV001585 > source, and you can find ViewBasket.jsp by expanding SV001585 > webApplication.
  7. Use the RecordIOManager bean from iSeries Java development tools to write an AddtoBasket servlet called by the Add to basket button, which updates the iSeries INVENTORY database by subtracting the quantity requested by the customer and adding the items to a Basket Java bean in the session. AddtoBasket.jsp code sample:
    public class AddtoBasket extends HttpServlet {
     
    	//Inner class of AddtoBasket
    	public class MyRecordIOManager extends RecordIOManager {
    		.
    		.
    		.
    		public MyRecordIOManager(
    					String hostInfo1,
    					String hostInfo2,
    					String hostInfo3,
    					String file,
    					String lib)throws Exception{
    			super(hostInfo1, hostInfo2,hostInfo3,file,lib);	
    			setFileAccessType(RecordIOManager.FILEACCESS_KEYED);
    			setCommitLockLevel(RecordIOManager.COMMITLOCKLEVEL_ALL);
    			//journal has the same name as the database file
    			setJournal(file);
    			//journal is in the same library as the database file
    			setJournalLibrary(lib);		
    		}	
    		.
    		.
    		.	
    		public synchronized String updateDBFile(
    			String id,
    			String size,
    			String quantity
    			) {
    			.
    			.
    			.
    			//opening the file
    			try {
    				if (openFile()) {
    					record = readRecord(key);
    					quantityAvailable = ((BigDecimal) 			
    						record.getValueAt(0,sizeColumn)).intValue();
    					totalQuantityAvailable = ((BigDecimal) 
    						record.getValueAt(0, 8)).intValue();
    					if (quantityRequested <= quantityAvailable) {
    						newQuantity = 
    						   new BigDecimal(quantityAvailable - quantityRequested);
    						totalNewQuantity = 
    						   new BigDecimal
    							(totalQuantityAvailable - quantityRequested);
    						record.setValueAt(newQuantity, 0, sizeColumn);
    						record.setValueAt(totalNewQuantity, 0, 8);
    						// Note that we update the record but we don't commit
    						// in case the customer decides to 
    						// empty the basket in which
    						// case we call the rollBack method
    						updateRecord(record);
    						status = success;
    					} else {
    						status = notEnough;
    					}
    				} else
    					status = accessError;
    			} catch (Exception e) {
    				e.printStackTrace();
    				status = accessError;
    			}
     
    			//closing the file and adding 
    			try {
    				closeFile();
    			} catch (Exception e) {
    				//in case of error rollback
    				try {
    					rollback();
    				} catch (Exception e1) {
    					e1.printStackTrace();
    				}
    				status = accessError;
    			}
     
    			return status;
    		}
    	}
     
    	//init method of AddtoBasket servlet
    	public void init() {
    		hostInfo = GetItems.getHostInfo();
    		
    	}
    	
    	public void doGet(HttpServletRequest req, 
       HttpServletResponse res) {
    		.
    		.
    		.
    		Basket basket = (Basket) session.getAttribute("basket");
    		MyRecordIOManager recIO = 
    		(MyRecordIOManager) session.getAttribute("recIO");
    		if (basket == null) {
    			basket = new Basket();
    			session.setAttribute("basket", basket);
    		}
     
    		if(recIO == null){
    			if (recIO == null) {
    			try {
    				recIO =
    					new MyRecordIOManager(
    						hostInfo[0],
    						hostInfo[1],
    						hostInfo[2],
    						GetItems.getInventoryFile(),
    						GetItems.getRetailLibrary());
    			} catch (Exception e) {
    				try {
    					res.sendRedirect("errorPage.html");
    					return;
    				} catch (Exception e1) {
    					e1.printStackTrace();
    				}
    			}
    		}	
    		id = req.getParameter("id");
    		size = req.getParameter(id + "S");
    		quantity = req.getParameter(id + "Q");
    		
    		status = recIO.updateDBFile(id, size, quantity);
    		session.setAttribute("recIO", recIO);
    			
    		if (status.equals("SUCCESS")) {
    			basket.addItem(id, quantity, size);
    			try {
    				res.sendRedirect("ViewBasket.jsp");
    				return;
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		} else {
    			if (status.equals("NOT_ENOUGH")) {
    				try {
    					res.sendRedirect("insufficient.html");
    					return;
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			} else
    				if (status.equals("ACCESS_ERROR")) {
    					try {
    						res.sendRedirect("errorPage.html");
    						return;
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
     
    		}
     
    	}
     
    
  8. Write a ViewBasket JSP file that displays the contents of the basket.
  9. Write a customerinfo.html form for the entering of payment information, including a Continue button that invokes ViewForConfirm.jsp.
  10. Write a ViewForConfirm.jsp that shows contents of the entire basket plus the total balance. You can develop ViewForConfirm.jsp in the same manner as ViewBasket.jsp, with the addition of a calculated shipping charge and a Confirm button that places an order in the iSeries ORDERS database.
  11. Use the iSeries Program Call wizard of iSeries Java development tools to create a PLACEORD.java bean, which accesses the PLACEODR service program in the RETAILSTOR library. The wizard creates beans for use by Java applications or the Web Services wizard to access iSeries ILE programs.
    1. To open the wizard, right-click SV001585 in the Navigator view and select New > Other.
    2. In the New window, click iSeries > Java > Program Call Bean.
    3. In the Program Call wizard, you enter information about the iSeries ILE program name, library, type of program, input and output parameters.
    4. The last window of the wizard gives you the option to create a bean for a Java application, a Web service, or both. In this project, you only need to create one for a Java application.
    Note:
    The PLACEODR service program takes an array of structures and places each element into one record of an ORDERS database, generating one order number as output for each array.
  12. Write a PlaceOrder servlet invoked by the ViewForConfirm.jsp Confirm button.

    The following code segment shows how the PlaceOrder servlet uses the PLACEORD bean:

    .
    	.
    	.
    	public void init() throws ServletException {
    		hostInfo = GetItems.getHostInfo();
    		super.init();
     
    		try {
    			/* creating an instance of the PLACEORD bean created 
    			   by iSeries Program Call Bean wizard */
    			orderBean = new PLACEORD();
    			orderBean.setConnectionData(hostInfo[0], 
    			hostInfo[1], hostInfo[2]);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	.
    	.
    	.
     
    	public void doPost(HttpServletRequest request, 
    	HttpServletResponse response) {
     
    		...
     
    		PLACEORD.Orditems_Struct inputStruct = null;
     
    		// retrieving the order items from the basket
    		Basket basket = 
    		(Basket) request.getSession().getAttribute("basket");
    		AddtoBasket.MyRecordIOManager recIO = 
    		(AddtoBasket.MyRecordIOManager) 		
    		  request.getSession().getAttribute("recIO");
    		if (basket == null || basket.size() == 0 
    		|| recIO == null) {
    			try {
    				response.sendRedirect("errorPage.html");
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		} else {
    			items = basket.elements();
    			// setting array of structure elements
    			while (items.hasMoreElements()) {
    				item = (String[]) items.nextElement();
    				inputStruct = orderBean.getOrdItemAr(j);
    				inputStruct.setItemNo(new BigDecimal(item[0]));
    				inputStruct.setQuantity(new BigDecimal(item[1]));
    				inputStruct.setSizeOrd(item[2]);
    				j = j + 1;
    			}
    			// setting the rest of the array elements to dummy values
    			for (int i = j - 1; i < 100; i++) {
    				inputStruct = orderBean.getOrdItemAr(i);
    				inputStruct.setItemNo(new BigDecimal(0));
    				inputStruct.setQuantity(new BigDecimal(0));
    				inputStruct.setSizeOrd("s");
    			}
    			
    			// setting the other two input parameters of the bean
    			orderBean.setNumOfItems(new BigDecimal(j));
    			orderBean.setBalance((BigDecimal) 
    			request.getSession().getAttribute("balance"));
    			try {
    				// invoking the iSeries program
    				orderBean.invoke();
    				
    				// retrieving the order number from PLACEORD bean
    				orderNumber = (orderBean.getRetCode()).toString();
    				request.getSession().setAttribute("orderNumber", 
    				orderNumber);
    				basket.empty();
    				// commit this order now 
    				recIO.commit();
    				response.sendRedirect("orderNumber.jsp");
    				return;
    			} catch (Exception e) {
    				response.sendRedirect("errorPage.html");
    				e.printStackTrace();
    			}
     
    		}
    	} 
     
    
  13. Write an OrderNumber servlet that retrieves the number and displays it for the customer along with a confirmation message. If the customer has not added any items to his or her basket, ensure that an error page is returned instead.


[ Top of Page | Previous Page | Next Page | Table of Contents ]