需求:页面显示两个下拉列表,一个显示省,一个显示市,要求选择省的时候显示对应的市,不选择则后面的下拉列表不显示内容。本案例通过JSP+Servlet+Hibernate+MysqL完成
(1)编写JSP页面
<html> <head> <title>jsTest</title> <!-- 引入js文件 --> <script type="text/javascript" src="demo.js"></script> </head> <body> <select name="pro" id="pro" onchange="javascript:selectChange();"> <!-- 省份 --> <option value="">--请选择--</option> </select> <select name="city" id="city"> <!-- 城市 --> <option value="">--请选择--</option> </select> </body> </html>
(2)构建PO,Pro和City,Pro和City是一对多的关系,
public class Pro { private int id; private String proName; private Set<City> citySet = new HashSet<City>(); public Set<City> getCitySet() { return citySet; } public void setCitySet(Set<City> citySet) { this.citySet = citySet; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } } public class City { private int id; private String cityName; private Pro pro; public Pro getPro() { return pro; } public void setPro(Pro pro) { this.pro = pro; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public City(int id,String cityName) { super(); this.id = id; this.cityName = cityName; } public City() { super(); // TODO Auto-generated constructor stub } }
(3)创建PO的配置文件,在此之前要配置Hibernate的主配置文件
<hibernate-mapping package="cn.itcast.domain"> <class name="Pro" table="t_pro"> <id name="id" type="integer" column="id"> <generator class="native"></generator> </id> <property name="proName" type="string" column="proName"></property> <set name="citySet" cascade="save-update"> <key column="pro_id"></key> <one-to-many class="City"/> </set> </class> </hibernate-mapping> <hibernate-mapping package="cn.itcast.domain"> <class name="City" table="t_city"> <id name="id" type="integer" column="id"> <generator class="native"></generator> </id> <property name="cityName" type="string" column="cityName"></property> <many-to-one name="pro" class="Pro" column="pro_id"></many-to-one> </class> </hibernate-mapping>
(4)创建测试类添加数据
public class Test { public static void main(String[] args) { save(); } public static void save(){ Session session = SessionUtils.getCurrentSession(); Transaction transaction = session.beginTransaction(); try { //创建Pro对象 Pro pro = new Pro(); pro.setProName("河北"); City city1 = new City(); city1.setCityName("石家庄"); City city2 = new City(); city2.setCityName("廊坊"); City city3 = new City(); city3.setCityName("秦皇岛"); City city4 = new City(); city4.setCityName("邯郸"); City city5 = new City(); city5.setCityName("保定"); pro.getCitySet().add(city1); pro.getCitySet().add(city2); pro.getCitySet().add(city3); pro.getCitySet().add(city4); pro.getCitySet().add(city5); Pro pro2 = new Pro(); pro2.setProName("山东"); City city6 = new City(); city6.setCityName("济南"); City city7 = new City(); city7.setCityName("日照"); City city8 = new City(); city8.setCityName("青岛"); pro2.getCitySet().add(city6); pro2.getCitySet().add(city7); pro2.getCitySet().add(city8); session.save(pro); session.save(pro2); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); throw new RuntimeException(e.getMessage(),e); } } }
(5)DAO层实现
public class ProDao { /** * 获取所有的省份对象集合 * @return */ public List<Pro> getPro(){ Session session = SessionUtils.openSession(); Transaction transaction = session.beginTransaction(); try { Query query = session.createQuery("from Pro"); List<Pro> list = query.list(); transaction.commit(); return list; } catch (HibernateException e) { transaction.rollback(); throw new RuntimeException(e.getMessage(),e); } finally{ session.close(); } } /** * 通过省份名来获取省份对象 * @param pro * @return */ public Pro getProByName(String pro) { Session session = SessionUtils.openSession(); System.out.println(pro); Transaction transaction = session.beginTransaction(); try { Query query = session.createQuery("from Pro where proName=?"); query.setParameter(0,pro); Pro pro1 = (Pro) query.uniqueResult(); transaction.commit(); return pro1; } catch (HibernateException e) { transaction.rollback(); throw new RuntimeException(e.getMessage(),e); } finally{ session.close(); } } /** * 通过省份的id来获取各省的城市的信息,城市表的外键指向省份的id * @param id * @return */ public List<City> getCitysByProId(int id) { Session session = SessionUtils.openSession(); Transaction transaction = session.beginTransaction(); try { Query query = session.createQuery("from City where pro.id=?"); query.setParameter(0,id); List<City> citys = query.list(); transaction.commit(); return citys; } catch (HibernateException e) { transaction.rollback(); throw new RuntimeException(e.getMessage(),e); } finally{ session.close(); } } }
(6)Service层实现
public class ProService { private ProDao dao = new ProDao(); public List<Pro> getPro(){ return dao.getPro(); } public Pro getProByName(String pro) { return dao.getProByName(pro); } public List<City> getCitysByProId(int id) { return dao.getCitysByProId(id); } }
(7)WEB层实现
/** * 页面初始化时,获取第一个下拉列表的所有省份的servlet * @author Administrator * */ public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setContentType("text/xml"); PrintWriter out = response.getWriter(); ProService service = new ProService(); List<Pro> list = service.getPro(); XStream xst = new XStream(); xst.alias("province",Pro.class); xst.useAttributeFor(Pro.class,"id"); xst.useAttributeFor(Pro.class,"proName"); String xml = xst.toXML(list); response.getWriter().write(xml); } public void doPost(HttpServletRequest request,IOException { response.setContentType("text/xml"); PrintWriter out = response.getWriter(); } } /** * 页面初始化时,获取第一个下拉列表的所有省份的servlet * @author Administrator * */ public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request,IOException { response.setContentType("text/xml"); PrintWriter out = response.getWriter(); } }
(8)获取HibernateSession的工具类
public class SessionUtils { private static SessionFactory sessionFactory = null; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } public static Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } public static Session openSession(){ return sessionFactory.openSession(); } }
(9)编写js文件,当打开页面是初始化所有省份,当选择省份时在第二个下拉列表框中显示对应的城市。
//获取XMLHttpRequest对象的方法,此方法是固定方法。 function ajaxFunction(){ var xmlHttp; try{ // Firefox,Opera 8.0+,Safari xmlHttp=new XMLHttpRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; } //获取所有的省份的信息,添加到省份的下拉列表中 window.onload = function(){ //获取对象 var xmlHttp = ajaxFunction(); //打开链接 xmlHttp.open("get","../servlet/DemoServlet",true); //发送请求。 xmlHttp.send(null); //接收响应 xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ var docXml = xmlHttp.responseXML; var proXmlElements = docXml.getElementsByTagName("province"); for(var i=0;i<proXmlElements.length;i++){ var proEle = proXmlElements[i]; var proValue = proEle.getAttribute("proName"); var option = document.createElement("option"); option.setAttribute("value",proValue); var text = document.createTextNode(proValue); option.appendChild(text); var proElement = document.getElementById("pro"); proElement.appendChild(option); } } } } } //点击省份的下拉列表,当列表发生改变时,显示对应省份的城市 var selectChange = function(){ //每次改变的时候,都要将上次的清除,否则会累加到下面。 //清除动作。 var cityObj = document.getElementById("city"); var cityOptions = cityObj.getElementsByTagName("option"); for(var i=0;i<cityOptions.length;i++){ if(cityOptions[i].getAttribute("value")!=null){ cityObj.removeChild(cityOptions[i]); } i--; } var xmlHttp = ajaxFunction(); var obj = document.getElementById("pro");//定位id var index = obj.selectedIndex; // 选中索引 var proName = obj.options[index].text; // 选中文本 //var value = obj.options[index].value; // 选中值 //var proName = currentPro.getAttribute("value"); //建立连接 xmlHttp.open("get","../servlet/GetCityServlet?pro="+proName,true); //发送请求 xmlHttp.send(null); //接收响应 xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ //获取响应的xml文本。 var docXml = xmlHttp.responseXML; var cityEles = docXml.getElementsByTagName("city"); var cityElement = document.getElementById("city"); var oneOption = document.createElement("option"); oneOption.setAttribute("value",""); var oneText = document.createTextNode("--请选择--"); oneOption.appendChild(oneText); cityElement.appendChild(oneOption); for(var i=0;i<cityEles.length;i++){ var cityEle = cityEles[i]; var cityValue = cityEle.getAttribute("cityName"); //创建option节点 var option = document.createElement("option"); option.setAttribute("value",cityValue); //创建option内的文本节点。 var text = document.createTextNode(cityValue); //将文本节点添加到option节点上。 option.appendChild(text); //获取jsp中的城市下拉列表的节点,并将创建的option节点添加到select上 cityElement.appendChild(option); } } } } }原文链接:https://www.f2er.com/ajax/165643.html