本例展示在 Struts 的 Action 中,把查詢結果封裝成列表並以 JSON 格式返回給前端 Ajax 的寫法。
public ActionForward xsearch(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String parentId = request.getParameter("parentId");
String supplier = request.getParameter("supplier");
List itemList = new ArrayList();
if(parentId.equals("")){
parentId = "0";
}
Map map = new TawApTreeServlet().getTypeList(parentId, supplier);
for (Iterator rowIt = map.keySet().iterator(); rowIt.hasNext();) {
String id = (String) rowIt.next();
TawCommonsUIListItem uiitem = new TawCommonsUIListItem();
uiitem.setItemId(id);
uiitem.setText((String) map.get(id));
uiitem.setValue(id);
itemList.add(uiitem);
}
response.setContentType("text/xml;charset=UTF-8");
// 返回 JSON 對象
response.getWriter().print(JSONUtil.list2JSON(itemList));
return null;
}
要點:把每一條數據封裝成列表項加入集合,最後用 JSONUtil.list2JSON 把整個列表序列化為 JSON 字符串輸出;返回 null 表示不再走視圖解析,直接由 response 寫出結果。