Jquery Modal Forms with Struts 1.3

て烟熏妆下的殇ゞ 提交于 2019-12-03 08:31:49

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.

The backing framework really doesn't make much of a difference in terms of raw JavaScript/jQuery/Ajax.

You can return whatever you want from your Struts 1 action. If you want some JSON back like with a status or Flash message you can either write it directly to the response and return null instead of an ActionForward, or craft a JSP to have the content you want and set an appropriate header.

How the return value of the Ajax request is handled is all up to the client-side code: Struts 1 doesn't care what type of request it is; it will just spit back whatever it's configured to spit back.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!