Académique Documents
Professionnel Documents
Culture Documents
A Guidelines Document
Page 1 of 20
Table of Contents
Whats Ajax?....................................................................................................................... 3 Thinks about AJAX................................................................................................................3 AJAX is based on Web Standards............................................................................................3 AJAX is About Better Internet Applications...............................................................................4 How Ajax is Different............................................................................................................4 Basic AJAX Flow...................................................................................................................5 High Level Flow....................................................................................................................7 Modification done in Existing frame work for AJAX....................................................................8 Code to use and changes needed on UI files...........................................................................10 Where to Use Ajax in J2EE application?.................................................................................10 Example of dependent drop down select lists..........................................................................11 Example of a messaging......................................................................................................13 Example of Text hints/auto-completion..................................................................................15 References ....................................................................................................................................... 20 Summary.......................................................................................................................... 20
Page 2 of 20
Whats Ajax?
Ajax, shorthand for Asynchronous JavaScript and XML, is a Web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.
Page 4 of 20
We will first call the JavaScript function getDescription on onmouseover event. Here is the html code: <a href="/" onmouseover="getDescription(3,1)">Java & J2EE News<a> Here is the code for Javascript getDescription function: var url = 'http://localhost:8080/getDescription.jsp?channelId=' + channelId + '&itemId=' + itemId; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.onreadystatechange = processRequest; req.open("GET", url, true); req.send(null);
AJAX implementation in J2EE application Wipro Technologies Page 5 of 20
The XMLHttpRequest object will be doing the http connection to retrive the xml document. We will check to see if it is IE or not and create the XMLHttpRequest object. if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } Set the callback function, and send the HTTP "GET" request to the server for the xml document: req.onreadystatechange = processRequest; req.open("GET", url, true); req.send(null); The JSP will create the xml document with the appropriate description for the channel and item numbers. Check for the response code for the HTTP request. Status is 200 for "OK". function processRequest() { if (req.readyState == 4) { if (req.status == 200) { parseMessages(); } else { alert ( "Not able to retrieve description" ); } } } The readyState is 4 if the document is loaded. readyState Status Codes: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete Finally, we now parse the XML document to retrive and show the description. function parseMessages() { response = req.responseXML.documentElement; itemDescription = response.getElementsByTagName('description') [0].firstChild.data; alert(itemDescription); }
Page 6 of 20
Page 7 of 20
ajax.js
The ajax.js JavaScript file is available in \include folder which contains the script to identify the browser type and their XmlHttpRequestObject type. var xmlHttpRequestHandler = new Object(); xmlHttpRequestHandler.createXmlHttpRequest = function(){ var XmlHttpRequestObject; if (typeof XMLHttpRequest != "undefined"){ XmlHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject){ // look up the highest possible MSXML version var tryPossibleVersions=["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp",
"Microsoft.XMLHttp"];
for (i=0; i< tryPossibleVersions.length; i++){ try{ XmlHttpRequestObject = new ActiveXObject(tryPossibleVersions[i]); break; } catch (xmlHttpRequestObjectError){ //ignore } } } return XmlHttpRequestObject; }
Page 9 of 20
Page 10 of 20
Code changes in jsp file: <script src="<%=properties.DOCROOT%>include/ajax.js" type="text/javascript"></script> <script type="text/javascript"> function goPagerPackageAjax(){ // If not enough info entered, bypass call and just put dummy on screen if (document.isn.p_service_type_cd.value == "" || document.isn.p_coverage_type_cd.value == "" || document.isn.p_ownership_type_cd.value == "" || document.isn.p_unit_cd.value == "") { var selectText = "<select name='p_package_id' onChange=\"packageChanged();\">+ <option value='' selected>No Packages Found - Change Service Type, Coverage, Ownership, or Unit</option></select>+ <em class=\"required\">*</em>"; var div_handle = document.getElementById("pager_package_div"); //check if DIV element is found if(div_handle){ div_handle.innerHTML=''+selectText; return; } } var PAGE_SUCCESS = 200; var requestObject = xmlHttpRequestHandler.createXmlHttpRequest(); <% StringBuffer temp = new StringBuffer(); temp.append("var p_package_id="); if (ordPagerGroup != null) { temp.append("\""+ordPagerGroup.getPackageId("#")+"\""); } else { temp.append("\"\""); } %> <%=temp.toString()%> var param="p_ajax_action=getPagingPackages"+"&p_save_screen="+document.isn. p_save_screen.value+
AJAX implementation in J2EE application Wipro Technologies Page 11 of 20
"&p_service_type_cd="+document.isn.p_service_type_cd.value+ "&p_coverage_type_cd="+document.isn.p_coverage_type_cd.value+ "&p_ownership_type_cd="+document.isn.p_ownership_type_cd.value+ "&p_unit_cd="+document.isn.p_unit_cd.value+ "&p_networx_ind="+document.isn.p_networx_ind.value+ "&p_package_id="+p_package_id; requestObject = xmlHttpRequestHandler.createXmlHttpRequest(); requestObject.open("Get","<%=properties.SERVLETURL %>"+"?"+param,false); requestObject.send(null); if (requestObject.status==PAGE_SUCCESS){ var div_handle = document.getElementById("pager_package_div"); //check if DIV element is found if(div_handle){ div_handle.innerHTML=''+requestObject.responseText; if (localViewMode == true) { document.isn.p_package_id.disabled=true; } } } else{ alert ("Unable to retrieve Paging Packages"); } } </script>
Code changes in java file: public class { protected String getAjaxResponse(String p_ajax_action) throws Exception { String response = null; if ("getPagingPackages".equalsIgnoreCase(p_ajax_action)) { DropDownFromArrayTag tag = new DropDownFromArrayTag(); tag.setControlName("p_test"); tag.setEventMonitors("onChange=\"packageChanged();\""); tag.setSelectedKey(selectedPackageId); tag.setLabelValueBeanList(labelValueBeanList); return tag.buildDropDown();
Page 12 of 20
Example of a messaging
Ajax implemented for confirms the destination Access Id - band width and clears the destination Access Id functionalities.
Code changes in CSDS\DLD Move Inside screen jsp file: <script src="<%=properties.DOCROOT%>include/ajax.js" type="text/javascript"></script> <script type="text/javascript"> function callAjax(inPar){ var PAGE_SUCCESS = 200; var requestObject = xmlHttpRequestHandler.createXmlHttpRequest(); requestObject = xmlHttpRequestHandler.createXmlHttpRequest(); var url = "<%=properties.SERVLETURL%>" + "? p_ajax_action="+inPar+ "&p_save_screen="+document.isn.p_save_screen.value+ "&p_dest_access_id="+document.isn.p_dest_access_id.value+ "&p_order_id="+document.isn.p_order_id.value+ "&p_action="+inPar+ "&p_prod_grp_num="+document.isn.p_prod_grp_num.value; var waitMsg = launchClock('Confirming Band Width...', '150px', '300px'); requestObject.onreadystatechange= function(){ if(requestObject.readyState == 4){ waitMsg.close(); } }; requestObject.open("Get",url+ '&' + Math.random(),false); requestObject.send(null); if (requestObject.status==PAGE_SUCCESS){ if(requestObject.responseText.indexOf('confirmed') >1 && inPar == 'Confirm'){ document.isn.btn1.value ='Clear Destination Access ID'; document.isn.btn1.onclick=function anonymous () {callAjax("Clear")}; document.isn.p_dest_access_id.readOnly = true; document.isn.p_dest_access_id.className ='roInput';
AJAX implementation in J2EE application Wipro Technologies Page 13 of 20
} else if(inPar == 'Clear'){ document.isn.btn1.value ='Confirm Available Bandwidth'; document.isn.btn1.onclick=function anonymous () {callAjax("Confirm")}; document.isn.p_dest_access_id.value =''; document.isn.p_dest_access_id.readOnly =false; document.isn.p_dest_access_id.className =''; } alert(requestObject.responseText); } else{ } } Code changes in java file: public class { /** * getAjaxResponse method - sets pair of hidden fields used to determine onscreen actions * @param p_ajax_action * @return * @throws Exception */ protected String getAjaxResponse(String p_ajax_action) throws Exception { //Getting values from request object final String p_order_id = request.getParameter("p_order_id"); final String p_prod_grp_num = request.getParameter("p_prod_grp_num"); final String p_dest_access_id = request.getParameter("p_dest_access_id"); final String p_action = request.getParameter("p_action"); StringBuffer responseBuf = new StringBuffer(); try { if ("Clear".equalsIgnoreCase(p_action)) { // Calling method clear the destination id clearDestinationAccessId(p_order_id, p_prod_grp_num); responseBuf.append("Destination Access ID cleared successfully"); } else if ("Confirm".equalsIgnoreCase(p_action)) { // Calling method confirm the destination id if(!confirmAvailableBandwidth(p_order_id, p_prod_grp_num, p_dest_access_id)) { responseBuf.append("The bandwidth of the Destination Access ID \n" + " cannot support the Port Speed of the Source \n" + " Access ID. Please enter another Destination \n" + " Access Id."); } else {
AJAX implementation in J2EE application Wipro Technologies Page 14 of 20
Code changes in As User screen jsp file: Java script changes: <script src="<%=properties.DOCROOT%>include/ajax.js" type="text/javascript"></script> <script type="text/javascript"> var READY_STATE_COMPLETE = 4; var PAGE_SUCCESS = 200; function searchUsers() { var searchString = document.isn.p_search_string.value; var div_handle = document.getElementById("p_search_results"); if ((searchString == null) || (searchString == "")) { if(div_handle){ div_handle.innerHTML = '';
AJAX implementation in J2EE application Wipro Technologies Page 15 of 20
} return; } var requestHandler = xmlHttpRequestHandler.createXmlHttpRequest(); var url = "<%=properties.SERVLETURL%>" + "? p_ajax_action=searchUsers" + "&p_save_screen="+document.isn.p_save_screen.value+ "&p_search_string="+document.isn.p_search_string.value+ "&p_exclude_num="+document.isn.p_exclude_num.value; requestHandler.open("Get",url,false); requestHandler.send(null); var ready = requestHandler.readyState; var status = requestHandler.status; if(status == PAGE_SUCCESS){ if(div_handle){ div_handle.innerHTML = ''+requestHandler.responseText; } } else{ alert ("Unable to retrieve Users. ready code:" + ready + " status:" + status); } } var id = 0; function delay(){ if (id != 0){ clearTimeout(id); id = 0; } id = setTimeout("searchUsers()",2000); } // DSM: works on IE 5.0+ only. function keyB() { return window.event.keyCode != 13; } HTML changes: <tr> <td colspan="4">Enter Name or Userid: <input type="text" name="p_search_string" size="30" onkeyup="delay()" onkeypress="return keyB()"></td> </tr>
Page 16 of 20
/** * getAjaxResponse method * @param p_ajax_action * @return * @throws Exception */ protected final String getAjaxResponse(final String p_ajax_action) throws Exception { String response = null; if ("searchUsers".equalsIgnoreCase(p_ajax_action)) { String p_search_string = request.getParameter("p_search_string"); String p_exclude_num = request.getParameter("p_exclude_num"); response = getSearchResults(p_search_string, p_exclude_num); } return response;
/** * getSearchResults method * @param p_search_string p_exclude_num * @return String * @throws Exception */ private String getSearchResults(final String p_search_string, final String p_exclude_num) throws Exception { logger.debug("getSearchResults(): BEGIN"); Sql PreparedStatement PreparedStatement ResultSet ResultSet int int int String String String sql pstmt pstmt2 rs rs2 whereIndex whereIndex2 row_count = = = = = = = = null; null; null; null; null; 1; 1; 0;
sUpper = "%" + p_search_string.toUpperCase() + "%"; sLower = "%" + p_search_string.toLowerCase() + "%"; sqlWhere = "WHERE "AND "AND SEC_STATUS_CD = 'A' LNAME <> 'CUSTOMER' USER_GROUP_ID <> ? " + " + " +
Page 17 of 20
((LNAME LIKE ? OR FNAME LIKE ? OR USERID LIKE ?) OR (LNAME LIKE ? OR FNAME LIKE ? OR USERID LIKE ?))
// LIMIT SEARCH RESULTS TO FIRST 100 RECORDS RETURNED String sqlstr = "SELECT LNAME, " " FNAME, " " MI, " " USERID " "FROM SEC_USER " sqlWhere "AND ROWNUM <= 100 " "ORDER BY LNAME, FNAME, USERID";
// COUNT THE TOTAL RECORDS RETURNED FOR DISPLAY COUNT String sqlstr2 = "SELECT COUNT(*) " + "FROM SEC_USER " + sqlWhere; try { sql = new Sql(); StringBuffer control = new StringBuffer(); // EXECUTE THE SQL COUNT FIRST pstmt2 = sql.getConnection().prepareStatement(sqlstr2); pstmt2.setString(whereIndex2++, p_exclude_num); pstmt2.setString(whereIndex2++, sUpper); pstmt2.setString(whereIndex2++, sUpper); pstmt2.setString(whereIndex2++, sUpper); pstmt2.setString(whereIndex2++, sLower); pstmt2.setString(whereIndex2++, sLower); pstmt2.setString(whereIndex2++, sLower); rs2 = pstmt2.executeQuery(); while (rs2.next()) { row_count = rs2.getInt("COUNT(*)"); } if (row_count == 0) { control.append("<br><p align='center'>No records found. Please refine search.</p>"); return control.toString(); } if (row_count > 100) { control.append("<br><p align='center'>"+row_count+" records found. Only the first 100 are displayed, please refine search.</p>"); } // NOW EXECUTE THE ACTUAL SEARCH QUERY pstmt = sql.getConnection().prepareStatement(sqlstr);
AJAX implementation in J2EE application Wipro Technologies Page 18 of 20
pstmt.setString(whereIndex++, p_exclude_num); pstmt.setString(whereIndex++, sUpper); pstmt.setString(whereIndex++, sUpper); pstmt.setString(whereIndex++, sUpper); pstmt.setString(whereIndex++, sLower); pstmt.setString(whereIndex++, sLower); pstmt.setString(whereIndex++, sLower); rs = pstmt.executeQuery(); control.append("<select class='fixedformat' size='12' name='p_as_userid'>"); // FORMAT THE DISPLAY NAME AND BUILD THE SELECT BOX while (rs.next()) { String lastName = rs.getString("LNAME").substring(0,1) + rs.getString("LNAME").substring(1).toLowerCase(); String firstName = rs.getString("FNAME").substring(0,1) + rs.getString("FNAME").substring(1).toLowerCase(); String userId = rs.getString("USERID"); String sName = lastName + ", " + firstName; sName = sName.trim() + " --------------------------------------------------"; sName = sName.substring(0,50) + " (" + userId + ")"; control.append("<option value='"); control.append(userId); control.append("'>"); control.append(sName); control.append("</option>"); } control.append("</select>"); return control.toString(); } catch (Exception ex) { logger.fatal(ex.getMessage(),ex); logger.fatal(Util.getStackTraceAsString(ex)); throw new Exception(ex.getMessage() + " SQL: " + sqlstr, } finally { if (pstmt != null) { pstmt.close(); pstmt = null; } if (pstmt2 != null) { pstmt2.close(); pstmt2 = null; } if (sql != null) { sql.close();
AJAX implementation in J2EE application Wipro Technologies Page 19 of 20
ex);
sql = null;
References
http://java.sun.com/developer/technicalArticles/J2EE/AJAX/DesignStrategies/ http://www.baekdal.com/articles/Usability/XMLHttpRequest-guidelines http://java.sun.com/developer/technicalArticles/J2EE/webapp_1/ http://developers.sun.com/prodtech/portalserver/reference/techart/asynch_rendering. html http://adaptivepath.com/publications/essays/archives/000385.php
Summary
We dont need a lot of code to do for Ajax. There are some situations where an external message has to be called every time the page is viewed. The Paging Packages dropdown is a good fit for Ajax-style loading as its query depended on user selections and other parts of the screen did not need to be saved for its display. Since sample Ajax example is only sending a very small query string, retrieving a small amount of data from the database, and returning a String that is significantly smaller than the entire HTML response, the speed difference is dramatic. Therefore, not only is the speed faster for the user, but my network bandwidth, web, and database server loads are lower. Considering the Ajax response is always going to be a smaller subset of the page, it is naturally going to be faster. This would be a very nice thing to use in cases where user actions are needed to bring different data back to the screen. Since this can also be asynchronous, it is possible to use this to submit long-running processes that dont require the user to wait but that they want confirmation on a conclusion of the process.
Page 20 of 20