原生Ajax级联菜单
在用户填写地址的时候,可能选择省份,而后在选择对应的城市,此时我们应让出现的可选城市都在选好的省份中。
1.VO类
package com.ajax.vo;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Province implements Serializable{
private Integer prid;
private String proName;
private String spell;
//方法略
}
package com.ajax.vo;
import java.io.Serializable;
@SuppressWarnings("serial")
public class City implements Serializable {
private Integer cid;
private String cName;
private Integer prid;
//方法略
}
2.数据层
package com.ajax.dbc;
import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
public class DBConnection {
private static DruidDataSource ds = null;
static{
try{
ds = new DruidDataSource();
// 2. 设置连接数据的信息(四要素)
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT");
ds.setUsername("root");
}catch(Exception e){
e.printStackTrace();
}
}
public static DataSource getDs(){
return ds;
}
public static Connection getConnection(){
Connection con = null;
try{
con = ds.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return con;
}
public static void close(Connection con){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
package com.ajax.dao;
import com.ajax.vo.City;
import java.sql.SQLException;
import java.util.List;
public interface ICityDAO {
public List<City> findAllByCRID(int CRID)throws SQLException;
}
package com.ajax.dao;
import com.ajax.vo.Province;
import java.sql.SQLException;
import java.util.List;
public interface IProvinceDAO {
public List<Province> findAll() throws SQLException;
}
package com.ajax.dao.impl;
import com.ajax.dao.ICityDAO;
import com.ajax.dbc.DBConnection;
import com.ajax.vo.City;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class CityDAOImpl implements ICityDAO{
@Override
public List<City> findAllByCRID(int CRID) throws SQLException {
String sql = "SELECT CID,CName,PRID FROM city WHERE PRID=?";
QueryRunner queryRunner = new QueryRunner(DBConnection.getDs());
return queryRunner.query(sql,new BeanListHandler<City>(City.class),CRID);
}
}
package com.ajax.dao.impl;
import com.ajax.dao.IProvinceDAO;
import com.ajax.dbc.DBConnection;
import com.ajax.vo.Province;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class ProvinceDAOImpl implements IProvinceDAO {
@Override
public List<Province> findAll() throws SQLException {
String sql = "SELECT PRID,ProName,Spell FROM province";
QueryRunner runner = new QueryRunner(DBConnection.getDs());
return runner.query(sql,new BeanListHandler<Province>(Province.class));
}
}
3.业务层
package com.ajax.service;
import com.ajax.vo.City;
import java.util.List;
public interface ICityService {
public List<City> listByPRID(int PRID);
}
package com.ajax.service;
import com.ajax.vo.Province;
import java.util.List;
public interface IProvinceService {
public List<Province> list();
}
package com.ajax.service.impl;
import com.ajax.factory.DAOFactory;
import com.ajax.service.ICityService;
import com.ajax.vo.City;
import java.util.List;
public class CityServiceImpl implements ICityService {
@Override
public List<City> listByPRID(int PRID) {
try{
return DAOFactory.getICityDAOInstance().findAllByCRID(PRID);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
package com.ajax.service.impl;
import com.ajax.factory.DAOFactory;
import com.ajax.service.IProvinceService;
import com.ajax.vo.Province;
import java.util.List;
public class ProvinceServiceImpl implements IProvinceService {
@Override
public List<Province> list() {
try{
return DAOFactory.getIProvinceDAOInstance().findAll();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
4.工厂类
package com.ajax.factory;
import com.ajax.dao.ICityDAO;
import com.ajax.dao.IProvinceDAO;
import com.ajax.dao.impl.CityDAOImpl;
import com.ajax.dao.impl.ProvinceDAOImpl;
public class DAOFactory {
public static IProvinceDAO getIProvinceDAOInstance(){
return new ProvinceDAOImpl();
}
public static ICityDAO getICityDAOInstance(){
return new CityDAOImpl();
}
}
package com.ajax.factory;
import com.ajax.service.ICityService;
import com.ajax.service.IProvinceService;
import com.ajax.service.impl.CityServiceImpl;
import com.ajax.service.impl.ProvinceServiceImpl;
public class ServiceFactory {
public static IProvinceService getIProvinceServiceInstance(){
return new ProvinceServiceImpl();
}
public static ICityService getICityServiceInstance(){
return new CityServiceImpl();
}
}
5.控制器
package com.ajax.servlet;
import com.ajax.factory.ServiceFactory;
import com.ajax.vo.City;
import com.ajax.vo.Province;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Iterator;
@WebServlet(urlPatterns = "/AddressServlet/*")
public class AddressServlet extends HttpServlet {
private HttpServletRequest request;
private HttpServletResponse response;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.request = request;
this.response = response;
String methodName = request.getRequestURI().substring(
request.getRequestURI().lastIndexOf("/")+1);
try{
Method method = this.getClass().getMethod(methodName);
method.invoke(this);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
public void province(){
try {
this.request.setCharacterEncoding("UTF-8");
this.response.setCharacterEncoding("UTF-8");
this.response.setContentType("text/xml");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Iterator<Province> iter = ServiceFactory.getIProvinceServiceInstance().list().iterator();
Document document = DocumentHelper.createDocument();
Element provincesEle = document.addElement("provinces");
while(iter.hasNext()){
Province province = iter.next();
Element provinceEle = provincesEle.addElement("province");
provinceEle.addElement("PRID").setText(String.valueOf(province.getPrid()));
provinceEle.addElement("ProName").setText(province.getProName());
}
try {
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(this.response.getWriter(),format);
writer.write(document);
} catch (Exception e) {
e.printStackTrace();
}
}
public void city(){
try {
this.request.setCharacterEncoding("UTF-8");
this.response.setCharacterEncoding("UTF-8");
this.response.setContentType("text/xml");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Integer PRID = Integer.parseInt(this.request.getParameter("PRID"));
Iterator<City> iter = ServiceFactory.getICityServiceInstance().listByPRID(PRID).iterator();
Document document = DocumentHelper.createDocument();
Element citysEle = document.addElement("citys");
while(iter.hasNext()){
City city = iter.next();
Element cityEle = citysEle.addElement("city");
cityEle.addElement("CID").setText(String.valueOf(city.getCid()));
cityEle.addElement("cName").setText(city.getcName());
}
try {
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(this.response.getWriter(),format);
writer.write(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}
6.显示层
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page pageEncoding="UTF-8" %>
<%
String basePath = request.getScheme()+"://"+request.getServerName()
+":"+request.getServerPort()+request.getContextPath();
String cityPath = basePath+"/AddressServlet/city";
String provincePath = basePath+"/AddressServlet/province";
%>
<html>
<head>
<title>Address</title>
</head>
<body>
<label>省:</label>
<select id="province" >
<option value="0">====请选择省份====</option>
</select>
<label>市:</label>
<select id="city">
<option value="0">====请选择市====</option>
</select>
<script type="text/javascript">
var xmlHttpRequest;
function create(){
if(window.XMLHttpRequest){
xmlHttpRequest = new XMLHttpRequest();
}else{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
}
}
function createProvince(PRID,ProName){
var provinceEle = document.getElementById("province");
var optionEle = document.createElement("option");
optionEle.appendChild(document.createTextNode(ProName));
optionEle.setAttribute("value",PRID);
provinceEle.appendChild(optionEle);
}
function createCity(data){
var cityEle = document.getElementById("city");
var CIDEles = data.getElementsByTagName("CID");
var cNameEles = data.getElementsByTagName("cName");
for(var x=0;x<CIDEles.length;x++){
var CID = CIDEles[x].firstChild.nodeValue;
var CName = cNameEles[x].firstChild.nodeValue;
var optionEle = document.createElement("option");
optionEle.appendChild(document.createTextNode(CName));
optionEle.setAttribute("value",CID);
cityEle.appendChild(optionEle);
}
}
function clearAllCity(){
var cityEle = document.getElementById("city");
var optionEle = cityEle.getElementsByTagName("option");
var len = optionEle.length-1;
for(var x=0;x<len;x++){
cityEle.removeChild(optionEle[1]);
}
}
function loadCity(){
clearAllCity();
var PRID = document.getElementById("province").value;
xmlHttpRequest.open("post","<%=cityPath%>?PRID="+PRID);
xmlHttpRequest.send(null);
xmlHttpRequest.onreadystatechange = function(){
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
var data = xmlHttpRequest.responseXML;
createCity(data);
}
}
}
window.onload = function(){
create();
xmlHttpRequest.open("post","<%=provincePath%>");
xmlHttpRequest.send(null);
xmlHttpRequest.onreadystatechange = function(){
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
var data = xmlHttpRequest.responseXML;
var PRIDEles = data.getElementsByTagName("PRID");
var ProNameEles = data.getElementsByTagName("ProName");
for(var x=0;x<PRIDEles.length;x++){
var PRID = PRIDEles[x].firstChild.nodeValue;
var ProName = ProNameEles[x].firstChild.nodeValue;
createProvince(PRID,ProName);
}
}
};
document.getElementById("province").addEventListener("change",function(){
loadCity();
},false);
}
</script>
</body>
</html>
此时执行此程序,发现操作正常完成: