Jquery Modal Forms with Struts 1.3

后端 未结 2 1095
慢半拍i
慢半拍i 2021-02-10 14:48

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

相关标签:
2条回答
  • 2021-02-10 15:27

    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.

    0 讨论(0)
  • 2021-02-10 15: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.

    0 讨论(0)
提交回复
热议问题