20
AJAX implementation in J2EE Application  A Guidelines Document Prepared by Vijayakumar Varadharajan WIPRO Technologies. AJAX implementation in J2EE application Page 1 of 20 Wipro Technologies

AJAX Implementation in J2EE Applcation

Embed Size (px)

Citation preview

Page 1: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 1/20

AJAX implementation in

J2EE Application

 

A Guidelines Document

Prepared byVijayakumar VaradharajanWIPRO Technologies.

AJAX implementation in J2EE application Page 1 of 20

Wipro Technologies

Page 2: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 2/20

Table of Contents

What’s Ajax?.......................................................................................................................3Thinks about AJAX................................................................................................................3AJAX is based on Web Standards............................................................................................3

AJAX is About Better Internet Applications...............................................................................4How Ajax is Different............................................................................................................4Basic AJAX Flow...................................................................................................................5High Level Flow....................................................................................................................7

Modification done in Existing frame work for AJAX....................................................................8Code to use and changes needed on UI files...........................................................................10Where to Use Ajax in J2EE application?.................................................................................10Example of dependent drop down select lists..........................................................................11

Example of a messaging......................................................................................................13Example of Text hints/auto-completion..................................................................................15References.......................................................................................................................................20

Summary..........................................................................................................................20

AJAX implementation in J2EE application Page 2 of 20

Wipro Technologies

Page 3: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 3/20

What’s 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 behindthe 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, usingthe 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 informationfrom the server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and moreuser-friendly.

AJAX is a browser technology independent of web server software.

It’s a way to use JavaScript in the client’s browser to access server

functionality, either asynchronously or synchronously.

It’s a new name, it’s not a new technology. XMLHttpRequest has beenavailable since IE 5.0.

It has nothing to do with Java. It works because of the browser and theserver’s ability to handle XMLHttpRequests.

It’s not a framework, library, JAR, or something that has to be used on allpages in a site (although there are some optional utils).

It’s 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 dynamicallydisplay 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 objectis 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 thatrefers 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 Page 3 of 20

Wipro Technologies

Page 4: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 4/20

AJAX is About Better Internet ApplicationsWeb applications have many benefits over desktop applications,

They can reach a larger audience, they are easier to install and support, and easierto develop.

However, Internet applications are not always as "rich" and user-friendly astraditional desktop applications.

With AJAX, Internet applications can be made richer and more user-friendly.

How Ajax is DifferentAn 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 theserver. 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 Ajaxengine — written in JavaScript and usually tucked away in a hidden frame. This

engine is responsible for both rendering the interface the user sees andcommunicating with the server on the user’s behalf. The Ajax engine allows the

user’s 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 Page 4 of 20

Wipro Technologies

Page 5: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 5/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 Page 5 of 20

Wipro Technologies

Page 6: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 6/20

The XMLHttpRequest object will be doing the http connection to retrive the xmldocument. 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 xmldocument:

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 = loading2 = loaded

3 = interactive4 = 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 Page 6 of 20

Wipro Technologies

Page 7: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 7/20

High Level FlowIn existing framework java classes and JavaScript utilities are made available toaccommodate 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 XMLformatted 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 Page 7 of 20

Wipro Technologies

Page 8: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 8/20

Modification done in Existing frame work for AJAX

Abstract.java

Modified Abstract.pSaveScreen() to first check the p_ajax_action to see if ithas 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 classesto perform whatever action is necessary just like setScreenReferenceData() or

setScreenOrderData(). The String response from getAjaxResonse() is placed in theHTTP 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 Page 8 of 20

Wipro Technologies

Page 9: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 9/20

}}

out.println(pAjaxResponse);out.flush();

out.close();} // end returnAjaxResponse

ajax.js

The ajax.js JavaScript file is available in \include folder which contains thescript 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 Page 9 of 20

Wipro Technologies

Page 10: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 10/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 Ajaxvar requestObject =

xmlHttpRequestHandler.createXmlHttpRequest();requestObject.open("Get","<%=properties.SERVLETURL

%>"+"?"+param,fals e);requestObject.send(null);

……………..

Must implement the getAjaxResponse method in servlet classprotected String getAjaxResponse(String p_ajax_action)

throws Exception {………….}

Where to Use Ajax in J2EE application?

Validating Id’s 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 messagefrom external systems.

If a field’s dropdown data is dependent on one or more other selections onthe 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 Page 10 of 20

Wipro Technologies

Page 11: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 11/20

Example of dependent drop down select listsAjax implemented in Page Characteristics product screen for “Retrieve Packages” topull 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 screenif (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 Page 11 of 20

Wipro Technologies

Page 12: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 12/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) throwsException {

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 Page 12 of 20

Wipro Technologies

Page 13: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 13/20

Example of a messagingAjax implemented for confirms the destination Access Id - band width and clears thedestination 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 Page 13 of 20

Wipro Technologies

Page 14: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 14/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 usedto determine onscreen actions

* @param p_ajax_action

* @return* @throws Exception*/protected String getAjaxResponse(String p_ajax_action) throws

Exception {//Getting values from request objectfinal 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 idclearDestinationAccessId(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 idif(!confirmAvailableBandwidth(p_order_id,

p_prod_grp_num, p_dest_access_id)) {

responseBuf.append("The bandwidth of theDestination Access ID \n" +

" cannot support the Port Speed of theSource \n" +

" Access ID. Please enter anotherDestination \n" +

" Access Id.");}else {

AJAX implementation in J2EE application Page 14 of 20

Wipro Technologies

Page 15: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 15/20

responseBuf.append("Destination Access IDconfirmed 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 Page 15 of 20

Wipro Technologies

Page 16: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 16/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 Page 16 of 20

Wipro Technologies

Page 17: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 17/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, finalString p_exclude_num) throws Exception {

logger.debug("getSearchResults(): BEGIN"); 

Sql sql = null;PreparedStatement pstmt = null;PreparedStatement pstmt2 = null;ResultSet rs = null;ResultSet rs2 = null;int whereIndex = 1;

int whereIndex2 = 1;int row_count = 0;

 String sUpper = "%" + p_search_string.toUpperCase() + "%";String sLower = "%" + p_search_string.toLowerCase() + "%";

 String sqlWhere = "WHERE SEC_STATUS_CD = 'A' " +

"AND LNAME <> 'CUSTOMER' " +"AND USER_GROUP_ID <> ? " +

AJAX implementation in J2EE application Page 17 of 20

Wipro Technologies

Page 18: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 18/20

"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 RETURNEDString 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 COUNTString sqlstr2 = "SELECT COUNT(*) " +

"FROM SEC_USER " +

sqlWhere; 

try {sql = new Sql();

 StringBuffer control = new StringBuffer();

 // EXECUTE THE SQL COUNT FIRSTpstmt2 = 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 refinesearch.</p>");

// NOW EXECUTE THE ACTUAL SEARCH QUERYpstmt = sql.getConnection().prepareStatement(sqlstr);

AJAX implementation in J2EE application Page 18 of 20

Wipro Technologies

Page 19: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 19/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 BOXwhile (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,

ex);} 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 Page 19 of 20

Wipro Technologies

Page 20: AJAX Implementation in J2EE Applcation

7/27/2019 AJAX Implementation in J2EE Applcation

http://slidepdf.com/reader/full/ajax-implementation-in-j2ee-applcation 20/20

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 don’t 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-styleloading 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 significantlysmaller 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, itis 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 canalso be asynchronous, 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 theprocess.

AJAX implementation in J2EE application Page 20 of 20