Saturday, May 9, 2009

HelloWorld - Ajax, Struts

This is a simple HelloWorld example for Ajax & Struts. In this example, I have a rudimentary Ajax call to the server side Struts Action class.

JavaScript:

<SCRIPT language="javascript">
var xmlHttp;
function greet(name) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Critical Browser Error: Pls. close the browser & try again!");
return false;
}
// struts action call
var url = "sayHello.do";
url = url + "?name=" + name.value;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}

function stateChanged() {

if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var strutsResp = xmlHttp.responseText;
document.getElementById("strutsResp").innerHTML = strutsResp;
} else {
alert("Critical Browser Error: Pls. close the browser & try again!");
}
}
}

function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</SCRIPT>


HTML Form:

<form><!-- onchange='greet(this);'-->
<p><LABEL for="name">Name: <input type="text" name="name"
size="10" id="name" onchange='greet(this);'/></LABEL>
<input type="button" id="ok" value="OK"/>
</p>
</form>


Struts Config:

<!--Note: the response is fully cooked - no mapping required! -->
<action-mappings>
<action path="/sayHello" type="com.aj.helloajax.actions.SayHelloAction">
</action>
</action-mappings>


Struts Action Class:

public class SayHelloAction extends Action {

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

String name = (String)request.getParameter("name");
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<h2>Hello "+name+" !!</h2>");
out.flush();
response.flushBuffer();
//Note: the response is fully cooked - no mapping required!
return null;
}
}

No comments: