Vous êtes sur la page 1sur 20

AJAX implementation in J2EE Application

A Guidelines Document

Prepared by Vijayakumar Varadharajan WIPRO Technologies.

AJAX implementation in J2EE application Wipro Technologies

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

AJAX implementation in J2EE application Wipro Technologies

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.

Thinks about AJAX


AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly. AJAX is a browser technology independent of web server software. Its a way to use JavaScript in the clients browser to access server functionality, either asynchronously or synchronously. Its a new name, its not a new technology. XMLHttpRequest has been available since IE 5.0. It has nothing to do with Java. It works because of the browser and the servers ability to handle XMLHttpRequests. Its not a framework, library, JAR, or something that has to be used on all pages in a site (although there are some optional utils). Its a tool in the toolbox, use appropriately

AJAX is based on Web Standards


AJAX is based on the following web standards: XHTML (or HTML), CSS, for marking up and styling information. The DOM accessed with a client-side scripting language, especially ECMA Script implementations such as JavaScript and JScript, to dynamically display and interact with the information presented. The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in certain situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server. XML is sometimes used as the format for transferring data between the server and client, although any format will work, including preformatted HTML, plain text, JSON and even EBML. Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies together The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.
AJAX implementation in J2EE application Wipro Technologies Page 3 of 20

AJAX is About Better Internet Applications


Web applications have many benefits over desktop applications, They can reach a larger audience, they are easier to install and support, and easier to develop. However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications. With AJAX, Internet applications can be made richer and more user-friendly.

How Ajax is Different


An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary an Ajax engine between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the users behalf. The Ajax engine allows the users interaction with the application to happen asynchronously independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.

AJAX implementation in J2EE application Wipro Technologies

Page 4 of 20

Basic AJAX Flow


Sequence Diagram:

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); }

AJAX implementation in J2EE application Wipro Technologies

Page 6 of 20

High Level Flow


In existing framework java classes and JavaScript utilities are made available to accommodate the AJAX call from the browser. In the browser based on the user action, JavaScript preparing the AJAX call. Browser AJAX engine is capturing the call and converting into HTTP request. Server executing servlet to complete the business logic and send back the XML formatted output to the browser. Browser AJAX engine is capturing the XML data and throwing to JavaScript method. JavaScript updating to the browser interface with data returned from server.

AJAX implementation in J2EE application Wipro Technologies

Page 7 of 20

Modification done in Existing frame work for AJAX


Abstract.java Modified Abstract.pSaveScreen() to first check the p_ajax_action to see if it has been set. If it has, it skips the pSave and pView methods and performs the getAjaxResonse() method public abstract class { ... public final void pSaveScreen() { try { String p_ajax_action = request.getParameter("p_ajax_action"); if (p_ajax_action != null && p_ajax_action.length() > 0) { returnAjaxResponse(getAjaxResponse(p_ajax_action)); return; } super.pSaveScreen(); String p_next_screen = request.getParameter("p_next_screen"); String p_url = request.getParameter("p_url"); ... The getAjaxResonse() method is overridden by the descendant screen classes to perform whatever action is necessary just like setScreenReferenceData() or setScreenOrderData(). The String response from getAjaxResonse() is placed in the HTTP response and returned to the web client using returnAjaxResponse(). ... /** * Method to return a String response to an Ajax action that will * be sent back to browser. Descendant classes will override if used. * @param p_ajax_action The action to be performed. * @return The String to send back to the browser in the response. * @throws Exception */ protected String getAjaxResponse(String p_ajax_action) throws Exception { return null; } /** * Places the passed string in the response and sends it back to client. * @param pAjaxResponse Response string to send back */ private final void returnAjaxResponse(String pAjaxResponse) { if (out == null) { try { out = new PrintWriter(response.getOutputStream()); } catch (Exception ex) { logger.error("Error in " + this.getClass().getName() + ".returnAjaxResponse() " + ex.getMessage()); logger.error(Util.getStackTraceAsString(ex));
AJAX implementation in J2EE application Wipro Technologies Page 8 of 20

} } out.println(pAjaxResponse); out.flush(); out.close(); } // end returnAjaxResponse

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; }

AJAX implementation in J2EE application Wipro Technologies

Page 9 of 20

Code to use and changes needed on UI files


Must do following changes, <script src="<%=properties.DOCROOT%>include/ajax.js" type="text/javascript"></script> //To do the javascript changes to call Ajax var requestObject = xmlHttpRequestHandler.createXmlHttpRequest(); requestObject.open("Get","<%=properties.SERVLETURL %>"+"?"+param,fals e); requestObject.send(null); .. Must implement the getAjaxResponse method in servlet class protected String getAjaxResponse(String p_ajax_action) throws Exception { . }

Where to Use Ajax in J2EE application?


Validating Ids with external systems for One World Id, Service Id, Billing ID, Corp Id. Complex business validation required for user entered data. Minimal data fetching and updates on Database like confirming access Id bandwidth, clearing access Id Band width, fetching Dar user list, get message from external systems. If a fields dropdown data is dependent on one or more other selections on the screen, it is faster to just reload that field as opposed to submitting the form. Commonly entered text hints/auto-completion. If a query or a call to a remote message is going to take a long time that cannot be avoided, Ajax works well to manage the time a user waits for the call to return.

AJAX implementation in J2EE application Wipro Technologies

Page 10 of 20

Example of dependent drop down select lists


Ajax implemented in Page Characteristics product screen for Retrieve Packages to pull back a dropdown list that may or may not have entries based on the selection of four other fields.

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();

AJAX implementation in J2EE application Wipro Technologies

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

responseBuf.append("Destination Access ID confirmed successfully"); } } } catch(Exception e) { responseBuf.append(e.getMessage()); } return responseBuf.toString(); }

Example of Text hints/auto-completion


Ajax implemented in As User screen for fetching possible names automatically for the entering text in the text (onkeyup).

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>

AJAX implementation in J2EE application Wipro Technologies

Page 16 of 20

Code changes in As User screen java file: public class { . . .

/** * 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

AJAX implementation in J2EE application Wipro Technologies

"AND " " " " "

((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.

AJAX implementation in J2EE application Wipro Technologies

Page 20 of 20

Vous aimerez peut-être aussi