Ajax学习笔记-三级联动

前端之家收集整理的这篇文章主要介绍了Ajax学习笔记-三级联动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

wKiom1Q2m8GRuHAhAACI9GIF62k176.jpg

三个实体类

Location.java

publicclassLocation{
	privateIntegerlocation_id;
	privateStringcity;
	//...
}

Department.java

publicclassDepartment{
	privateIntegerdepartment_id;
	privateStringdepartmentName;
	privateIntegerlocation_id;
	//...
}

Employee.java

publicclassEmployee{
	privateIntegeremployeeId;
	privateStringlastName;
	privateStringemail;
	privatedoublesalary;
	privateIntegerdepartment_id;
	//...
}

WebContent下的emplooyes.jsp中只有一行代码跳转到servlet

<%
	response.sendRedirect("EmployeeServlet?method=listLocations");
%>

EmployeeServlet.java

publicclassEmployeeServletextendsHttpServlet{
	privatestaticfinallongserialVersionUID=1L;
	protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
		StringmethodName=request.getParameter("method");
		try{
			Methodmethod=getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(this,request,response);
		}catch(Exceptione){
			e.printStackTrace();
		}
	}
	
	
	protectedvoidlistLocations(HttpServletRequestrequest,IOException{
		Connectionconnection=DBManager.getConnection();
		Stringsql="select*fromlocation";
		List<Location>locations=newArrayList<Location>();
		Statementstatement=null;
		ResultSetresultSet=null;
		Locationlocation=null;
		try{
			statement=connection.createStatement();
			resultSet=statement.executeQuery(sql);
			while(resultSet.next()){
				location=newLocation();
				location.setCity(resultSet.getString("city"));
				location.setLocation_id(resultSet.getInt("location_id"));
				locations.add(location);
			}
		}catch(sqlExceptione){
			e.printStackTrace();
		}finally{
			DBManager.close(resultSet,statement,connection);
		}
		request.setAttribute("locations",locations);
		request.getRequestDispatcher("/WEB-INF/pages/employees.jsp").forward(request,response);
	}
	
	protectedvoidlistDepartments(HttpServletRequestrequest,IOException{
		intlocationId=Integer.parseInt(request.getParameter("locationId"));
		Stringsql="select*fromdepartmentwherelocation_id="+locationId;
		Connectionconnection=DBManager.getConnection();
		List<Department>departments=newArrayList<Department>();
		Departmentdepartment=null;
		ResultSetresultSet=null;
		Statementstatement=null;
		try{
			statement=connection.createStatement();
			resultSet=statement.executeQuery(sql);
			while(resultSet.next()){
				department=newDepartment();
				department.setDepartmentName(resultSet.getString("departmentName"));
				department.setDepartment_id(resultSet.getInt("department_id"));
				department.setLocation_id(resultSet.getInt("location_id"));
				departments.add(department);
			}
		}catch(sqlExceptione){
			e.printStackTrace();
		}finally{
			DBManager.close(resultSet,connection);
		}
		ObjectMappermapper=newObjectMapper();
		Stringresult=mapper.writeValueAsString(departments);
		System.out.println(result);
		response.setContentType("text/javascript");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(result);
	}
	
	protectedvoidlistEmployees(HttpServletRequestrequest,IOException{
		intdepartment_id=Integer.parseInt(request.getParameter("department_id"));
		Stringsql="select*fromemployeewheredepartment_id="+department_id;
		Connectionconnection=DBManager.getConnection();
		Statementstatement=null;
		ResultSetresultSet=null;
		List<Employee>employees=newArrayList<Employee>();
		Employeeemployee=null;
		try{
			statement=connection.createStatement();
			resultSet=statement.executeQuery(sql);
			while(resultSet.next()){
				employee=newEmployee();
				employee.setDepartment_id(resultSet.getInt("department_id"));
				employee.setEmail(resultSet.getString("email"));
				employee.setEmployeeId(resultSet.getInt("employee_id"));
				employee.setLastName(resultSet.getString("last_name"));
				employee.setSalary(resultSet.getDouble("salary"));
				employees.add(employee);
			}
		}catch(sqlExceptione){
			//TODOAuto-generatedcatchblock
			e.printStackTrace();
		}finally{
			DBManager.close(resultSet,connection);
		}
		ObjectMappermapper=newObjectMapper();
		Stringresult=mapper.writeValueAsString(employees);
		System.out.println(result);
		response.setContentType("text/javascript");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(result);
	}
	
	protectedvoidlistEmployeeInfo(HttpServletRequestrequest,IOException{
		intemployeeId=Integer.parseInt(request.getParameter("employeeId"));
		Stringsql="select*fromemployeewhereemployee_id="+employeeId;
		System.err.println(sql);
		Connectionconnection=DBManager.getConnection();
		Statementstatement=null;
		ResultSetresultSet=null;
		Employeeemployee=null;
		try{
			statement=connection.createStatement();
			resultSet=statement.executeQuery(sql);
			if(resultSet.next()){
				employee=newEmployee();
				employee.setDepartment_id(resultSet.getInt("department_id"));
				employee.setEmail(resultSet.getString("email"));
				employee.setEmployeeId(resultSet.getInt("employee_id"));
				employee.setLastName(resultSet.getString("last_name"));
				employee.setSalary(resultSet.getDouble("salary"));
			}
		}catch(Exceptione){
			e.printStackTrace();
		}finally{
			DBManager.close(resultSet,connection);
		}
		ObjectMappermapper=newObjectMapper();
		Stringresult=mapper.writeValueAsString(employee);
		System.out.println(result);
		response.setContentType("text/javascript");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(result);
	}
	
	publicstaticvoidmain(String[]args){
		System.out.println(DBManager.getConnection());
	}
}

/WEB-INF/pages/employees.jsp浏览器不可达,只能通过servlet跳转到该页面

<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>Inserttitlehere</title>
<scripttype="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-1.11.1.min.js"></script>
<scripttype="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery.blockUI.js"></script>
<scripttype="text/javascript">
	$(function(){
		$(document).ajaxStart(function(){
			//使用blockUI。ajax请求发出时执行
			$.blockUI({
			message:$('#loading'),css:{
				top:($(window).height()-400)/2+'px',left:($(window).width()-400)/2+'px',width:'400px'
			},overlayCSS:{backgroundColor:'#00f'}
			})
		}).ajaxStop($.unblockUI);
		
		
		$("#city").change(function(){
			$("#departmentoption:not(:first)").remove();
			varlocation_id=$(this).val();
			if(location_id!=""){
				varurl="EmployeeServlet?method=listDepartments";
				varargs={"locationId":location_id,"time":newDate()};
				
				$.getJSON(url,args,function(data){
					if(data.length==0){
						alert("当前城市没有部门");
					}else{
						for(vari=0;i<data.length;i++){
							vardeptName=data[i].departmentName;
							vardeptId=data[i].department_id;
							//alert(deptName);
							$("#department").append("<optionvalue='"+deptId+"'>"+deptName+"</option>");
						}
					}
				});
			}
		});
		$("#department").change(function(){
			$("#employeeoption:not(:first)").remove();
			vardepartment_id=$(this).val();
			if(department_id!=""){
				varurl="EmployeeServlet?method=listEmployees";
				varargs={"department_id":department_id,"time":newDate()};
				$.getJSON(url,function(data){
					if(data.length==0){
						alert("当前部门没有员工");
					}else{
						for(vari=0;i<data.length;i++){
							varlastName=data[i].lastName;
							varemail=data[i].email;
							varsalary=data[i].salary;
							varemployeeId=data[i].employeeId;
							$("#employee").append("<optionvalue='"+employeeId+"'>"+lastName+"</option>");
						}
					}
				});
			}
		});
		$("#employee").change(function(){
			varemployeeId=$(this).val();
			if(employeeId!=""){
				varurl="EmployeeServlet?method=listEmployeeInfo";
				varargs={"employeeId":employeeId,function(data){
					if(data.length==0){
						alert("数据丢失");
					}else{
						$("#employee_id").text(data.employeeId);
						$("#last_name").text(data.lastName);
						$("#email").text(data.email);
						$("#salary").text(data.salary);
					}
				});
			}
			//}
		});
	})
</script>
</head>
<body>
	<imgalt=""id="loading"src="${pageContext.request.contextPath}/images/loading.gif"style="display:none">
	City:
	<selectid="city">
		<optionvalue="">请选择...</option>
		<c:forEachitems="${locations}"var="location">
			<optionvalue="${location.location_id}">${location.city}</option>
		</c:forEach>
	</select>Department:
	<selectid="department">
		<optionvalue="">请选择...</option>
	</select>Employee:
	<selectid="employee">
		<optionvalue="">请选择...</option>

	</select>
	<br/>员工编号:
	<spanid="employee_id"></span>
	<br/>姓名:
	<spanid="last_name"></span>
	<br/>email:
	<spanid="email"></span>
	<br/>薪水:
	<spanid="salary"></span>
	<br/>
</body>
</html>

源码http://yunpan.cn/cgephkTV2Tcmh (提取码:2492)

本文出自 “优赛工作室博客,请务必保留此出处http://www.jb51.cc/article/p-stlvkshz-qg.html

原文链接:https://www.f2er.com/ajax/162441.html

猜你在找的Ajax相关文章