You are on page 1of 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

What’s 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

including preformatted HTML. or something that has to be used on all pages in a site (although there are some optional utils). or SPA. without reloading the page. Thinks about AJAX   AJAX is not a new programming language. allowing web pages to request small bits of information from the server instead of whole pages. shorthand for Asynchronous JavaScript and XML.0. speed. This is meant to increase the web page's interactivity. for marking up and styling information. use appropriately         AJAX is based on Web Standards    AJAX is based on the following web standards: XHTML (or HTML). In some Ajax frameworks and in certain situations. to dynamically display and interact with the information presented. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server. It’s a new name. so that the entire web page does not have to be reloaded each time the user makes a change. The DOM accessed with a client-side scripting language. CSS. With this object. and usability. AJAX applications are browser and platform independent. It’s a way to use JavaScript in the client’s browser to access server functionality. and more interactive web applications. either asynchronously or synchronously. it’s not a new technology.What’s Ajax? Ajax. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes. XMLHttpRequest has been available since IE 5. using the JavaScript XMLHttpRequest object. LAMP. your JavaScript can communicate directly with the server. It’s a tool in the toolbox. XML is sometimes used as the format for transferring data between the server and client. AJAX implementation in J2EE application Wipro Technologies Page 3 of 20     . With AJAX. and supported by all major browsers. plain text. AJAX is a browser technology independent of web server software. Ajax is not a technology in itself. an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server. JAR. The AJAX technique makes Internet applications smaller. It works because of the browser and the server’s ability to handle XMLHttpRequests. Like DHTML. especially ECMA Script implementations such as JavaScript and JScript. but a technique for creating better. your JavaScript can trade data with a web server. JSON and even EBML. although any format will work. faster. but a term that refers to the use of a group of technologies together The web standards used in AJAX are well defined. It has nothing to do with Java. The XMLHttpRequest object to exchange data asynchronously with the web server. It’s not a framework. library. faster and more user-friendly. is a Web development technique for creating interactive web applications.

Internet applications are not always as "rich" and user-friendly as traditional desktop applications. waiting around for the server to do something. They can reach a larger audience. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server.AJAX is About Better Internet Applications Web applications have many benefits over desktop applications. the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. However. Internet applications can be made richer and more user-friendly. Instead of loading a webpage. So the user is never staring at a blank browser window and an hourglass icon. With AJAX. at the start of the session. they are easier to install and support. AJAX implementation in J2EE application Wipro Technologies Page 4 of 20 . and easier to develop. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. It seems like adding a layer to the application would make it less responsive. 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. but the opposite is true.

XMLHttpRequest) { req = new XMLHttpRequest(). url.send(null). req.Basic AJAX Flow Sequence Diagram: We will first call the JavaScript function getDescription on onmouseover event. AJAX implementation in J2EE application Wipro Technologies Page 5 of 20 . req. } req. true). Here is the html code: <a href="/" onmouseover="getDescription(3. if (window.1)">Java & J2EE News<a> Here is the code for Javascript getDescription function: var url = 'http://localhost:8080/getDescription.open("GET".XMLHTTP").onreadystatechange = processRequest. } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.jsp?channelId=' + channelId + '&itemId=' + itemId.

and send the HTTP "GET" request to the server for the xml document: req. function processRequest() { if (req. The JSP will create the xml document with the appropriate description for the channel and item numbers. url. Check for the response code for the HTTP request. } Set the callback function. if (window. } else if (window. true).getElementsByTagName('description') [0]. readyState Status Codes: 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete Finally. req. Status is 200 for "OK". req. } AJAX implementation in J2EE application Wipro Technologies Page 6 of 20 .ActiveXObject) { req = new ActiveXObject("Microsoft.responseXML. function parseMessages() { response = req. } else { alert ( "Not able to retrieve description" ).onreadystatechange = processRequest.documentElement.status == 200) { parseMessages().XMLHTTP"). itemDescription = response. we now parse the XML document to retrive and show the description.open("GET". alert(itemDescription).XMLHttpRequest) { req = new XMLHttpRequest().firstChild. } } } The readyState is 4 if the document is loaded.data.readyState == 4) { if (req.send(null). We will check to see if it is IE or not and create the XMLHttpRequest object.The XMLHttpRequest object will be doing the http connection to retrive the xml document.

JavaScript updating to the browser interface with data returned from server. JavaScript preparing the AJAX call.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. Browser AJAX engine is capturing the call and converting into HTTP request. AJAX implementation in J2EE application Wipro Technologies Page 7 of 20 . Browser AJAX engine is capturing the XML data and throwing to JavaScript method. Server executing servlet to complete the business logic and send back the XML formatted output to the browser.

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

i++){ try{ XmlHttpRequestObject = new ActiveXObject(tryPossibleVersions[i]). if (typeof XMLHttpRequest != "undefined"){ XmlHttpRequestObject = new XMLHttpRequest(). out.} } out. } AJAX implementation in J2EE application Wipro Technologies Page 9 of 20 . "MSXML2.println(pAjaxResponse). "MSXML2.js JavaScript file is available in \include folder which contains the script to identify the browser type and their XmlHttpRequestObject type. "MSXML2. break. var xmlHttpRequestHandler = new Object().XMLHttp".XMLHttp. } // end returnAjaxResponse ajax. for (i=0.createXmlHttpRequest = function(){ var XmlHttpRequestObject.4.0".0".XMLHttp"].3.flush(). out. "Microsoft.ActiveXObject){ // look up the highest possible MSXML version var tryPossibleVersions=["MSXML2.5.close(). i< tryPossibleVersions.XMLHttp. } catch (xmlHttpRequestObjectError){ //ignore } } } return XmlHttpRequestObject.XMLHttp.0".js The ajax. xmlHttpRequestHandler. } else if (window.length.

Minimal data fetching and updates on Database like confirming access Id bandwidth. If a query or a call to a remote message is going to take a long time that cannot be avoided.    AJAX implementation in J2EE application Wipro Technologies Page 10 of 20 .fals e). }  Where to Use Ajax in J2EE application?    Validating Id’s with external systems for One World Id.Code to use and changes needed on UI files Must do following changes.. Corp Id….SERVLETURL %>"+"?"+param. requestObject. ……………. Billing ID.open("Get".createXmlHttpRequest(). If a field’s dropdown data is dependent on one or more other selections on the screen. get message from external systems."<%=properties. Service Id. fetching Dar user list. Complex business validation required for user entered data. Ajax works well to manage the time a user waits for the call to return. clearing access Id Band width. <script src="<%=properties.js" type="text/javascript"></script> //To do the javascript changes to call Ajax var requestObject = xmlHttpRequestHandler.send(null).  Must implement the getAjaxResponse method in servlet class protected String getAjaxResponse(String p_ajax_action) throws Exception { …………. requestObject. Commonly entered text hints/auto-completion. it is faster to just reload that field as opposed to submitting the form.DOCROOT%>include/ajax.

p_unit_cd.p_service_type_cd. p_save_screen.js" type="text/javascript"></script> <script type="text/javascript"> function goPagerPackageAjax(){ // If not enough info entered.isn.value+ AJAX implementation in J2EE application Wipro Technologies Page 11 of 20 .append("var p_package_id=").\">”+ ”<option value='' selected>No Packages Found .innerHTML=''+selectText.DOCROOT%>include/ajax.createXmlHttpRequest(). //check if DIV element is found if(div_handle){ div_handle.isn.toString()%> var param="p_ajax_action=getPagingPackages"+"&p_save_screen="+document. <% StringBuffer temp = new StringBuffer(). } %> <%=temp. Ownership.isn. var requestObject = xmlHttpRequestHandler.getElementById("pager_package_div").p_ownership_type_cd. Code changes in jsp file: <script src="<%=properties. temp. bypass call and just put dummy on screen if (document.value == "" || document. or Unit</option></select>”+ ”<em class=\"required\">*</em>".value == "" || document.getPackageId("#")+"\"").value == "" || document.Change Service Type. return. if (ordPagerGroup != null) { temp. var div_handle = document. } } var PAGE_SUCCESS = 200.p_coverage_type_cd.value == "") { var selectText = "<select name='p_package_id' onChange=\"packageChanged(). Coverage.isn.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.append("\"\"").append("\""+ordPagerGroup. } else { temp.isn.

requestObject.isn.equalsIgnoreCase(p_ajax_action)) { … DropDownFromArrayTag tag = new DropDownFromArrayTag().p_service_type_cd.disabled=true.value+ "&p_coverage_type_cd="+document.p_unit_cd. tag. requestObject. if (requestObject.p_package_id.value+ "&p_unit_cd="+document. } } } 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.false)."<%=properties. tag.setEventMonitors("onChange=\"packageChanged().send(null). if (localViewMode == true) { document.isn.p_networx_ind.SERVLETURL %>"+"?"+param. … AJAX implementation in J2EE application Wipro Technologies Page 12 of 20 . if ("getPagingPackages". tag.p_ownership_type_cd.isn.buildDropDown().value+ "&p_ownership_type_cd="+document.value+ "&p_package_id="+p_package_id.status==PAGE_SUCCESS){ var div_handle = document.\"").open("Get". tag.setControlName("p_test").getElementById("pager_package_div")."&p_service_type_cd="+document. //check if DIV element is found if(div_handle){ div_handle.setSelectedKey(selectedPackageId).responseText.value+ "&p_networx_ind="+document.isn.isn.p_coverage_type_cd. requestObject = xmlHttpRequestHandler.innerHTML=''+requestObject.createXmlHttpRequest(). return tag.setLabelValueBeanList(labelValueBeanList).isn.

p_save_screen.isn.random().value+ "&p_dest_access_id="+document.status==PAGE_SUCCESS){ if(requestObject.band width and clears the destination Access Id functionalities. document.value+ "&p_action="+inPar+ "&p_prod_grp_num="+document.p_dest_access_id.indexOf('confirmed') >1 && inPar == 'Confirm'){ document.className ='roInput'.p_prod_grp_num.value+ "&p_order_id="+document. requestObject = xmlHttpRequestHandler. var url = "<%=properties. if (requestObject. } }. var waitMsg = launchClock('Confirming Band Width.isn.p_order_id.responseText.btn1.'.DOCROOT%>include/ajax.isn.readyState == 4){ waitMsg.p_dest_access_id. var requestObject = xmlHttpRequestHandler.isn.value ='Clear Destination Access ID'.isn.createXmlHttpRequest().createXmlHttpRequest().isn.send(null).Example of a messaging Ajax implemented for confirms the destination Access Id .onclick=function anonymous () {callAjax("Clear")}. Code changes in CSDS\DLD Move Inside screen jsp file: <script src="<%=properties..false).p_dest_access_id.js" type="text/javascript"></script> <script type="text/javascript"> function callAjax(inPar){ var PAGE_SUCCESS = 200.btn1.open("Get".readOnly = true. '150px'. '300px').SERVLETURL%>" + "? p_ajax_action="+inPar+ "&p_save_screen="+document.close().value. AJAX implementation in J2EE application Wipro Technologies Page 13 of 20 . requestObject.onreadystatechange= function(){ if(requestObject.isn. requestObject. document. requestObject.url+ '&' + Math.isn. document..

value =''.p_dest_access_id. } else if ("Confirm". } alert(requestObject.} else if(inPar == 'Clear'){ document.append("Destination Access ID cleared successfully"). p_dest_access_id)) { responseBuf. document.p_dest_access_id. StringBuffer responseBuf = new StringBuffer().value ='Confirm Available Bandwidth'.isn.onclick=function anonymous () {callAjax("Confirm")}. try { if ("Clear".isn.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. final String p_action = request.getParameter("p_prod_grp_num"). final String p_dest_access_id = request. final String p_prod_grp_num = request. p_prod_grp_num.isn.btn1.isn."). } else{ } } Code changes in java file: public class { … /** * getAjaxResponse method .getParameter("p_dest_access_id").btn1.getParameter("p_action"). responseBuf.responseText). } else { AJAX implementation in J2EE application Wipro Technologies Page 14 of 20 .readOnly =false. Please enter another Destination \n" + " Access Id. document. p_prod_grp_num).isn.append("The bandwidth of the Destination Access ID \n" + " cannot support the Port Speed of the Source \n" + " Access ID.equalsIgnoreCase(p_action)) { // Calling method confirm the destination id if(!confirmAvailableBandwidth(p_order_id. document. document.className =''.equalsIgnoreCase(p_action)) { // Calling method clear the destination id clearDestinationAccessId(p_order_id.getParameter("p_order_id").p_dest_access_id.

DOCROOT%>include/ajax. var div_handle = document.toString().getMessage()).responseBuf.append(e. } return responseBuf. function searchUsers() { var searchString = document.js" type="text/javascript"></script> <script type="text/javascript"> var READY_STATE_COMPLETE = 4.getElementById("p_search_results"). Code changes in ‘As User’ screen jsp file: Java script changes: <script src="<%=properties. if ((searchString == null) || (searchString == "")) { if(div_handle){ div_handle.value.append("Destination Access ID confirmed successfully").p_search_string. var PAGE_SUCCESS = 200.isn. } } } catch(Exception e) { responseBuf.innerHTML = ''. AJAX implementation in J2EE application Wipro Technologies Page 15 of 20 . } 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).

false). } 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 . function keyB() { return window.createXmlHttpRequest().isn.0+ only. } id = setTimeout("searchUsers()". } var requestHandler = xmlHttpRequestHandler. var status = requestHandler.readyState.p_save_screen. } } else{ alert ("Unable to retrieve Users.p_search_string.value+ "&p_exclude_num="+document.status. var ready = requestHandler. id = 0. if(status == PAGE_SUCCESS){ if(div_handle){ div_handle. } // DSM: works on IE 5.} return. var url = "<%=properties.isn.SERVLETURL%>" + "? p_ajax_action=searchUsers" + "&p_save_screen="+document. requestHandler.isn.send(null). } } var id = 0. function delay(){ if (id != 0){ clearTimeout(id).event.value.open("Get". ready code:" + ready + " status:" + status).p_exclude_num.2000).url.keyCode != 13.innerHTML = ''+requestHandler. requestHandler.responseText.value+ "&p_search_string="+document.

sqlWhere = "WHERE "AND "AND SEC_STATUS_CD = 'A' LNAME <> 'CUSTOMER' USER_GROUP_ID <> ? " + " + " + Page 17 of 20 AJAX implementation in J2EE application Wipro Technologies . 1. /** * getAjaxResponse method * @param p_ajax_action * @return * @throws Exception */ protected final String getAjaxResponse(final String p_ajax_action) throws Exception { String response = null. null. final String p_exclude_num) throws Exception { logger. String p_exclude_num = request. } return response.toUpperCase() + "%". sLower = "%" + p_search_string. Sql PreparedStatement PreparedStatement ResultSet ResultSet int int int String String String sql pstmt pstmt2 rs rs2 whereIndex whereIndex2 row_count = = = = = = = = null.getParameter("p_exclude_num"). null.Code changes in ‘As User’ screen java file: public class { .equalsIgnoreCase(p_ajax_action)) { String p_search_string = request.debug("getSearchResults(): BEGIN"). 0. null. p_exclude_num). } /** * getSearchResults method * @param p_search_string p_exclude_num * @return String * @throws Exception */ private String getSearchResults(final String p_search_string. null. 1.toLowerCase() + "%". response = getSearchResults(p_search_string. if ("searchUsers". sUpper = "%" + p_search_string.getParameter("p_search_string"). . .

next()) { row_count = rs2. AJAX implementation in J2EE application Wipro Technologies Page 18 of 20 ."AND " " " " " ((LNAME LIKE ? OR FNAME LIKE ? OR USERID LIKE ?) OR (LNAME LIKE ? OR FNAME LIKE ? OR USERID LIKE ?)) " + " + " + " + " + ".append("<br><p align='center'>"+row_count+" records found. " " MI.setString(whereIndex2++. please refine search.setString(whereIndex2++.getInt("COUNT(*)"). try { sql = new Sql().</p>"). StringBuffer control = new StringBuffer().prepareStatement(sqlstr2).setString(whereIndex2++. } // NOW EXECUTE THE ACTUAL SEARCH QUERY pstmt = sql. // COUNT THE TOTAL RECORDS RETURNED FOR DISPLAY COUNT String sqlstr2 = "SELECT COUNT(*) " + "FROM SEC_USER " + sqlWhere. Please refine search.getConnection().setString(whereIndex2++. + + + + + + + // LIMIT SEARCH RESULTS TO FIRST 100 RECORDS RETURNED String sqlstr = "SELECT LNAME. sUpper). sLower).getConnection(). Only the first 100 are displayed. pstmt2.</p>"). sUpper). FNAME.setString(whereIndex2++. rs2 = pstmt2. pstmt2. " " USERID " "FROM SEC_USER " sqlWhere "AND ROWNUM <= 100 " "ORDER BY LNAME. return control. sUpper).setString(whereIndex2++. pstmt2. USERID".setString(whereIndex2++. sLower). } if (row_count == 0) { control. p_exclude_num). sLower). while (rs2.prepareStatement(sqlstr).append("<br><p align='center'>No records found. pstmt2. } if (row_count > 100) { control. " " FNAME.executeQuery(). pstmt2.toString(). // EXECUTE THE SQL COUNT FIRST pstmt2 = sql. pstmt2. pstmt2.

ex). control.close(). sLower).substring(1). pstmt. control.getString("USERID"). sName = sName.setString(whereIndex++.append("'>"). } if (sql != null) { sql. control.toLowerCase().getMessage() + " SQL: " + sqlstr. sLower). pstmt. pstmt. throw new Exception(ex. logger.append("<select class='fixedformat' size='12' name='p_as_userid'>"). pstmt.append("<option value='").executeQuery().append("</select>").close(). String userId = rs. rs = pstmt. pstmt. } catch (Exception ex) { logger. } control.getString("FNAME"). sUpper).getString("FNAME").1) + rs. pstmt = null. } if (pstmt2 != null) { pstmt2. .setString(whereIndex++. return control. pstmt2 = null.append(sName). control.fatal(Util.1) + rs. AJAX implementation in J2EE application Wipro Technologies Page 19 of 20 ex). pstmt. control. sLower).setString(whereIndex++.append(userId).next()) { String lastName = rs.setString(whereIndex++. sName = sName. p_exclude_num). " + firstName.getStackTraceAsString(ex)). sUpper). String firstName = rs.getString("LNAME"). String sName = lastName + ".substring(0.pstmt.trim() + " --------------------------------------------------".substring(0.substring(0.substring(1).close().50) + " (" + userId + ")".toString().append("</option>"). sUpper).getString("LNAME"). } finally { if (pstmt != null) { pstmt. control. // FORMAT THE DISPLAY NAME AND BUILD THE SELECT BOX while (rs.toLowerCase().setString(whereIndex++.getMessage().setString(whereIndex++.setString(whereIndex++.fatal(ex.

sun.com/developer/technicalArticles/J2EE/AJAX/DesignStrategies/ http://www. Since sample Ajax example is only sending a very small query string. html http://adaptivepath. web. and database server loads are lower. References • • • • • http://java. AJAX implementation in J2EE application Wipro Technologies Page 20 of 20 . the speed difference is dramatic. it is naturally going to be faster. but my network bandwidth. it is possible to use this to submit long-running processes that don’t require the user to wait but that they want confirmation on a conclusion of the process. retrieving a small amount of data from the database.} sql = null. Therefore.com/prodtech/portalserver/reference/techart/asynch_rendering.baekdal. and returning a String that is significantly smaller than the entire HTML response. Considering the Ajax response is always going to be a smaller subset of the page.com/developer/technicalArticles/J2EE/webapp_1/ http://developers. This would be a very nice thing to use in cases where user actions are needed to bring different data back to the screen.sun. 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. There are some situations where an external message has to be called every time the page is viewed.sun. Since this can also be asynchronous.com/publications/essays/archives/000385.php Summary We don’t need a lot of code to do for Ajax.com/articles/Usability/XMLHttpRequest-guidelines http://java. not only is the speed faster for the user.