需求:建立3级列表联动 城市->部门->员工 点击员工弹出员工具体的信息表
思路:
1.首先因为是3级,所以需要在数据库内建立3张表格,而且注意要“级联”哦。因为要通过外键,来知道第一个表的所对应的部门
2.建立每个表相对应的javaBean。
3.写一个Dao类来完成城市数据的导入。
具体代码如下
public class SelectDao { private Connection conn=null; private Statement statement=null; public List getLocationds(String sql){ Locations loca=null; List listLocations=null; try { conn=ConnectionUtil.getConnection(); //sql语句查询出数据 //String sql="select * from locations"; //获得查询是否有结果得到的集合 statement=conn.createStatement(); ResultSet rs=statement.executeQuery(sql); //创建一个用于存储数据locations的集合 listLocations=new ArrayList(); System.out.println("aa"); while(rs.next()){ // loca=new Locations(); loca.setCity_name(rs.getString("city_name")); loca.setLocations_id((rs.getInt("locations_id"))); System.out.println(loca.getLocations_id()); System.out.println(loca.getCity_name()); //将存储的对象加入集合当中 listLocations.add(loca); } //释放此ReslutSet对象的数据库和jdbc资源 rs.close(); //释放PreparedStatement对象的数据库和jdbc资源 statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //关闭数据库链接 ConnectionUtil.closeConnection(conn); } return listLocations; }
ConnectionUtil是我写的数据库链接工具类
这个方法返回的是存储着城市对象的集合
4.编写一个视图层 写一个jsp页面
具体的代码如下,这里是我3级联动前端全部的代码我没有裁减
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'select.jsp' starting page</title> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-3.2.0.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery.blockUI.js"></script> <script type="text/javascript"> $(document).ajaxStart(function(){$.blockUI({ message:$('#loading'), css:{ top: ($(window).height()-400)/2+'px', left:($(window).width()-400)/2+'px', '400px', border:'none' }, overlayCSS:{ backgroundColor:'#fff' } })}).ajaxStop($.unblockUI); /* 1.导入jquery库 2.获取选择框,给框添加onchange事件 3.首先一开始要判断select里是否含有option,因为如果你已经选了其他的再进去选得时候原来选得不会没有,还会在那里,所以 就要判断一开始那个省的选择框是否为空,如果为空说明选的是“请选择”,不发送ajax请求 4.准备发送json请求,url,args 5.服务器发回来的肯定是json数组,一开始还要进行判断,因为有可能没有部门。如果没有部门就进行弹出框 6.得到你要输出的select的id进行输出 */ $(function(){ /*sheng dao city start */ $('#sheng').change(function(){ //判断城市是否为空,清空城市的原来所选的 $('#city option:not(:first)').remove(); //alert("a"); //this指代你所选的那个框 var sheng=$(this).val(); if(sheng!=""){ var url="LocationsServlet?method=departmentslist"; var args={"locations_id":sheng,"time":new Date()}; $.getJSON(url,args,function(data){ //判断是否有部门,由于返回的是数组所以有长度 if(data.length==0){ alert("这个省份没有城市"); } //遍历这个数组咯 for(var i=0;i<data.length;i++){ var depart_name=data[i].depart_name; var depart_id=data[i].depart_id; $('#city').append("<option value='"+depart_id+"'>"+depart_name+"</option>") } }); } }); /* end sheng to city */ /* city to area start */ /* 1.给城市添加onchange事件 2.去除出第一个以外的所有的,之前选的 3.判断选择的是否为空如果为空则说明“请选择”,则不发送ajax请求; 4.如果不为空则发送ajax请求 5.url LocationsServlet?method=employeeslist 6.args depart_id time 7.返回的是一个json数组 8.有可能没有地方所以进行判断 9.给select添加option 10.给地方添加onchange事件 11.给表格添加选中的地方的数据 */ $('#city').change(function(){ //去除选中的数据除第一行外 $('#area option:not(:first)').remove(); //得到option对象的值 var city=$(this).val(); alert(this.innerHTML); //alert("aa") if(city!=""){ var url="LocationsServlet?method=employeeslist"; var args={"depart_id":city,"time":new Date()}; $.getJSON(url,args,function(data){ //判断是否有地方 if(data.length==0){ alert("这个城市没有这个地方"); } else{ //遍历这个数组 for(var i=0;i<data.length;i++){ var em_id=data[i].em_id; var em_name=data[i].em_name; var em_age=data[i].em_age; //为了实现下面通过id获取name和age等属性值 //alert($(this).className); //得到你要输出的对象 var opNode=document.createElement("option"); //$('#area').append("<option value='"+em_id+"'>"+em_name+"</option>"); //为当前对象设置属性值 opNode.value=em_id; opNode.appendChild(document.createTextNode(em_name)); //alert(opNode.className); var tableNode=document.getElementById("area"); tableNode.appendChild(opNode); $(opNode).attr("em_id",em_id); $(opNode).attr("em_name",em_name); $(opNode).attr("em_age", em_age); //给地方添加change事件 //alert($(opNode).attr("em_id")); } //通过option在select的角标和data的角标 //获取#area节点 /* var areaNode=document.getElementById("area"); var optionNodes=areaNode.getElementsByTagName("option"); //遍历这个数组 alert("aa"); for(var i;i<optionNodes.length;i++){ $(function(){ //给每一个option添加change事件 $(optionNodes[i]).click(function(){ alert("a"); $('#table tr:not(:first)').remove(); $('#table').append("<tr><td>" + $(optionNodes[i]).attr("em_id") + "</td><td>" + $(optionNodes[i]).attr("em_name") + "</td><td>" + $(optionNodes[i]).attr("em_age") + "</td></tr>"); $('#table').show(); }); }); } */ $('#area').change(function() { //清空之前选的数据 $('#table tr:not(:first)').remove(); $('#table').show(); alert($(this).val()); alert(this.selectedIndex); //alert($(this).attr("em_id")); //alert((this.options[this.selectedIndex]).); alert(this.innerHTML); $('#table').append("<tr><td>" + $(this.options[this.selectedIndex]).attr("em_id") + "</td><td>" + $(this.options[this.selectedIndex]).attr("em_name") + "</td><td>" + $(this.options[this.selectedIndex]).attr("em_age") + "</td></tr>"); }); } }); } }); /* end city to area */ }); </script> </head> <body> <img alt="" src="images/1.gif" style="display:none" id="loading"> <div> <%-- <jsp:useBean id="is" class="com.jdztc.ajax.javabean.Locations"></jsp:useBean> --%> <span>我大中国的省:</span> <select id="sheng"> <option value="">请选择...</option> <c:forEach items="${locations}" var="location"> <option value="${location.locations_id}">${location.city_name}</option> </c:forEach> </select> <span>城市名:</span> <select id="city"> <option value="">请选择...</option> </select> <span>地方:</span> <select id="area"> <option value="">请选择...</option> </select> <br/> <table style="display:none" id="table" border="1px solid" height="50px" width="150px" align="center"> <th colspan="3">difang</th> </table> </div> </body> </html>
5.编写一个导入城市数据的servlet控制层
这个servlet实现了一个servlet处理多个请求,发送多个响应的功能,通过在url后面添加数据的形式实现
这里还用到了反射,思想和具体的代码如下
package com.jdztc.ajax.servlet; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.databind.ObjectMapper; import com.jdztc.ajax.dao.SelectDao; import com.jdztc.ajax.javabean.Departments; import com.jdztc.ajax.javabean.Employees; import com.jdztc.ajax.javabean.Locations; /** * 一个servlet处理多个请求不必要每个请求进行写一个servlet这样不能体现代码的复用性; *所以在servlet中建立处理的方法然后根据反射进行调用 *对各个功能进行封装 * @author 付鹏鹏 * */ public class LocationsServlet extends HttpServlet{ private SelectDao sd=new SelectDao(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub /** * 通过反射进行调用locationlist方法; * 反射机制:首先的得得到方法名 * 2.在通过类文件得到方法区, * 3.调用这个方法 */ //得到方法名 String methodname=req.getParameter("method"); //得到类文件中的方法区中的对象 try { Method method=getClass().getDeclaredMethod(methodname,HttpServletRequest.class,HttpServletResponse.class); //这个方法o指代发送请求的那个请求想要调用哪个方法的对象,指当前进入这个post请求的对象(这个类的新实例) /*Object o=getClass().newInstance(); method.invoke(o,req,resp);*/ method.invoke(this,req,resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void locationslist(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ //设置req和resp的编码格式 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); // //获取存取数据的集合实例化Dao //sql语句 String sql="select * from locations"; List<Locations> locations=sd.getLocationds(sql); /* for(int i=0;i<locations.size();i++){ System.out.println("get"+locations.get(i).getCity_name()); } */ //设置locations属性 req.getSession().setAttribute("locations", locations); //将消息转发送至select.jsp页面 req.getRequestDispatcher("/app3/select.jsp").forward(req, resp); } protected void departmentslist(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ // 设置req和resp的编码格式 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //得到对应省份的id int locations_id=Integer.parseInt(req.getParameter("locations_id")); System.out.println(locations_id); String sql="select * from departments where location_id=?"; List<Departments> listdepart=sd.getdepartments(sql,locations_id); System.out.println("listdepart集合:"+listdepart); //引用jackson插件使集合成json对象数组 ObjectMapper mo=new ObjectMapper(); String result=mo.writeValueAsString(listdepart); //将结果输出 System.out.println(result); resp.getWriter().println(result); } protected void employeeslist(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ // 设置req和resp的编码格式 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //得到depart_id int depart_id=Integer.parseInt(req.getParameter("depart_id")); String sql="select * from employees where depart_id=?"; //得到从数据库中返回的数据 List<Employees> listemployee=sd.getemployees(sql,depart_id); //使用jackson插件使集合生成json对象数组 ObjectMapper om=new ObjectMapper(); String result=om.writeValueAsString(listemployee); //将结果发出 resp.getWriter().println(result); } @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); } }
7.城市到部门
导入数据和方式一样,这里主要讲一下jsp脚本的思路
.给城市添加onchange事件
2.去除出第一个以外的所有的,之前选的
3.判断选择的是否为空如果为空则说明“请选择”,则不发送ajax请求;
4.如果不为空则发送ajax请求
5.url LocationsServlet?method=employeeslist
6.args depart_id time
7.返回的是一个json数组
8.有可能没有地方(这里指员工)所以进行判断
9.给select添加option
10.给地方添加onchange事件
11.给表格添加选中的地方的数据
思路是一样的。
实现功能
点击option弹出员工的具体信息表
给表添加onchange事件
注意在onchange事件当中的当前对象不是你选中的option而是option的集合
所以需要通过这样$(this.options[this.selectedIndex])才能得到你选中的option对象
之前的“em_id”属性已经设置具体的代码如下
$('#area').change(function() { //清空之前选的数据 $('#table tr:not(:first)').remove(); $('#table').show(); alert($(this).val()); alert(this.selectedIndex); //alert($(this).attr("em_id")); //alert((this.options[this.selectedIndex]).); alert(this.innerHTML); $('#table').append("<tr><td>" + $(this.options[this.selectedIndex]).attr("em_id") + "</td><td>" + $(this.options[this.selectedIndex]).attr("em_name") + "</td><td>" + $(this.options[this.selectedIndex]).attr("em_age") + "</td></tr>"); });