I\'m builing a web application using Struts 1.3 for a class project, and I\'m having some problems with the AJAX compatibility of Struts 1.x (I hear 2.x is way better with AJAX
One thing, if you want to return data outside of an ActionForward
, you must return null
. When Struts sees a null ActionForward
, it doesn't execute the forward.
Once done, the following type design is what I used to create a JSON Response in Struts:
public interface Result {
public void applyResult(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
public abstract class ResultBasedAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Result result = execute(mapping, form, request);
if (result == null) {
throw new Exception("Result expected.");
}
result.applyResult(request, response);
//Finally, we don't want Struts to execute the forward
return null;
}
public abstract Result execute(ActionMapping mapping, ActionForm form, HttpServletRequest request) throws Exception;
}
public class JsonResult implements Result {
private JSONObject json;
public JsonResult(JSONObject json) {
this.json = json;
}
public void applyResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Type", "application/json");
response.getOutputStream().write(json.toString().getBytes("UTF-8"));
response.getOutputStream().flush();
}
}
All your AJAX related responses will implement the ResultBasedAction
for action, and a Result
for the data to be sent to the client.
On your ajax, you will just have to do an HTTP GET
, passing all parameters on the URL. Make sure that the parameters matches your Struts ActionForm
for the required Action
class.