有一件事,如果你想返回ActionForward
以外的數據,你必須return null
。當Struts看到一個空值ActionForward
時,它不執行轉發。
一旦完成,以下類型的設計是我用來創建Struts中的JSON響應:
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();
}
}
你所有的AJAX相關的應答將實施ResultBasedAction
行動,以及Result
的數據是發送給客戶。
在你的ajax上,你只需要做一個HTTP GET
,傳遞URL上的所有參數。請確保參數與您的Struts ActionForm
匹配所需的Action
類。
什麼課程讓你使用Struts 1? –
是的,我知道,這太可怕了!我將向你的TA發表你的評論:P – nicohvi
(而且我是一個提交者......但是Struts 1已經過時了,使得創建現代的,可測試的軟件變得非常困難。) –