Ajax with Struts the Dojo Way

Tutorial Requirements

My Index.jsp Index.jsp

My action class action class

Here I am using my jsp from previous post.Hopefully you people have noticed the user() function and there lies the call to ajax from the widget.It just calls an action class function.

Here with no prompting,I have used the DispatchAction method to execute my ajax call(That doesnt matter here).I am concentrating on the ajax side.

My script containing function user is:

<script type=”text/javascript”>
function user(){
dojo.xhrPost( {
url: “/path.do?func=ajax”,
handleAs: “text”,
load: function(response) {
alert(response);
}
}
);}
</script>

here I will explain from

dojo.xhrPost which itself is a function

It submits a HTTP POST request asynchronously. Use xhrPost when you want to send form data to a website and the form doesn’t contain any file-input fields. (use dojo.io.iframe.send() instead)

[taken from:http://www.dojoforum.com/2007/10/11/dojo-example-xhrget-and-xhrpost]

Its arguments

url:to which url the request is forwarded:

In this case path.do is my action class ======> /path

handleAs:text tells the response to be handled as a text

load:function(response) causes the function to be loaded directly on returning successfully from the servlet(our controller class and everything works fine).

Here i havent included any arguments in my url except the hardcoded func=ajax

(We can do so) specifying parameters as the second argument.

which selects the function to be called in the action class,wait I will explain about my action class shortly.

My action class

public ActionForward ajax(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward(); // return value
FormBean formBean = (FormBean) form;

try {
PrintWriter p=  response.getWriter();
p.println(“Hi im using ajax”);

} catch (Exception e) {

errors.add(“name”, new ActionError(“id”));

}

if (!errors.isEmpty()) {
saveErrors(request, errors);
}
forward = mapping.findForward(“success”);

return (null);

}

Now you have noticed we have returned null instead of the forward string,that does the trick.

PrintWriter p=  response.getWriter();
p.println(“Hi im using ajax”); is used to output response .

Hope you have got a clear picture.

And now the result page is:

Leave a Reply