Prototype Ajax with Apache Struts

Posted by anup.narkhede on February 20, 2007

A simple example of Ajax on Struts using prototype.js

ScrapLogger is a simple example of integrating prototype and scriptaculous effects with struts. The logger is a demonstration of single ajax updater call, and scriptaculous Highlight effect.
My Java struts application contain a single action class, one form bean and two JSPs.

snapshot

ActionClass: LogScrap.java

public class LogScrap extends Action {

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
InsertScrapFormBean insertScrapFormBean = (InsertScrapFormBean) form;

try {
System.out.println(insertScrapFormBean.getName()+” form”);
} catch (Exception e) {
errors.add(”name”, new ActionError(”id”));

}

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

}
}

2) FormBean: InsertScrapFormBean.java

public class InsertScrapFormBean extends ActionForm {

private String name = null;

public String getName() {
return name;
}

public void setName(String n) {
this.name = n; System.out.println(”in form bean “+ n);
}

public void reset(ActionMapping mapping, HttpServletRequest request) {
name = “”;
}

public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
return errors;

}
}

The Ajax request is called from index.jsp

Code Snippet:

function submitScrap()
{
new Ajax.Updater(’Scrapbook’, ‘/ScrapLogger/logScrap.do?name=’+document.getElementById(’name’).value,
{insertion: Insertion.Top});
new Effect.Highlight(’ScrapBook’);
}

Download Source and EAR

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments