日期:2014-05-16  浏览次数:20633 次

Ajax+struts实现级联菜单~学习笔记
1,数据库表

sheng(省份):id, uname; shi(市):id,uname,shengId;   xian(县):id,uname,xianId;

2,新建项目:menuDemo,并添加struts和hibernate引用。

3,创建各个表的dao层方法,返回为List集合,该部分省略。

4,创建MenuAction,继承DispatchAction;

package web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import dao.ShengDao;
import dao.ShiDao;
import dao.XianDao;
import entity.Shi;
import entity.Xian;

public class MenuAction extends DispatchAction {


public ActionForward searchCity(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {
   int id = Integer.parseInt(request.getParameter("id"));
   System.out.println(id);
   String searchType = request.getParameter("searchType");
//必须有这句话,负责页面不能解析xml文件
   StringBuffer responseXML = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  
    responseXML.append("<domains>");
   if(searchType.equals("shi")){
    ShiDao shiDao = new ShiDao();
    List list = shiDao.getShi(id);
    Iterator it = list.iterator();
    while(it.hasNext()){
     Shi shi = (Shi)it.next();
     responseXML.append("<domain");
     responseXML.append(" id='" + shi.getId());
     responseXML.append("'>");
     responseXML.append(shi.getUname());
     responseXML.append("</domain>");

    }
   }
   if(searchType.equals("xian")){
    XianDao xianDao = new XianDao();
    List list = xianDao.getXian(id);
    Iterator it = list.iterator();
    while(it.hasNext()){
     Xian xian = (Xian)it.next();
     responseXML.append("<domain");
     responseXML.append(" id='" + xian.getId());
     responseXML.append("'>");
     responseXML.append(xian.getUname());
     responseXML.append("</domain>");
    }
   }
   responseXML.append("</domains>");

   response.setContentType("text/xml; charset=UTF-8");
   response.setHeader("Cache-Control", "no-cache");

   try {
   PrintWriter out = (PrintWriter) response.getWriter();
    out.write(responseXML.toString());

    System.out.println(responseXML.toString());
    // out.flush();
   } catch (IOException e) {
    // do nothing
    e.printStackTrace();
   }
//返回空值,忽略struts-config.xml配置中的结果页
  return null;

}
public ActionForward showSheng(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {
   ShengDao shengDao = new ShengDao();