有一件事,如果你想返回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已经过时了,使得创建现代的,可测试的软件变得非常困难。) –