- create database linkage;
- use linkage;
- --省份
- create table province
- (
- pid int primary key,
- pname varchar(20)
- );
- insert into province(pid,pname) values(1,'吉林省');
- insert into province(pid,pname) values(2,'辽宁省');
- --城市
- create table city
- (
- cid int primary key,
- cname varchar(20),
- pid int
- );
- insert into city(cid,cname,pid) values(1,'长春',1);
- insert into city(cid,cname,pid) values(2,'四平',1);
- insert into city(cid,cname,pid) values(3,'大连',2);
- insert into city(cid,cname,pid) values(4,'鞍山',2);
- -- 乡镇
- create table town
- (
- tid int primary key,
- tname varchar(20),
- cid int
- );
- insert into town(tid,tname,cid) values(1,'九台',1);
- insert into town(tid,tname,cid) values(2,'农安',1);
- insert into town(tid,tname,cid) values(3,'梨树',2);
- insert into town(tid,tname,cid) values(4,'公主岭',2);
- insert into town(tid,tname,cid) values(5,'沙河口',3);
- insert into town(tid,tname,cid) values(6,'甘井子',3);
- insert into town(tid,tname,cid) values(7,'铁东',4);
- insert into town(tid,tname,cid) values(8,'立山',4);
2.创建实体对象
2.1省份
- package org.monday.domain;
- /**
- * 省份
- *
- * @author Monday
- */
- public class Province {
- private Integer pid;
- private String pname;
- public Integer getPid() {
- return pid;
- }
- public void setPid(Integer pid) {
- this.pid = pid;
- }
- public String getPname() {
- return pname;
- }
- public void setPname(String pname) {
- this.pname = pname;
- }
- }
2.2城市实体
- package org.monday.domain;
- /**
- * 城市
- *
- * @author Monday
- */
- public class City {
- private Integer cid;
- private String cname;
- private Integer pid;
- public Integer getCid() {
- return cid;
- }
- public void setCid(Integer cid) {
- this.cid = cid;
- }
- public String getCname() {
- return cname;
- }
- public void setCname(String cname) {
- this.cname = cname;
- }
- public Integer getPid() {
- return pid;
- }
- public void setPid(Integer pid) {
- this.pid = pid;
- }
- }
2.3乡镇实体
- package org.monday.domain;
- /**
- * 乡镇
- *
- * @author Monday
- */
- public class Town {
- private Integer tid;
- private String tname;
- private Integer cid;
- public Integer getTid() {
- return tid;
- }
- public void setTid(Integer tid) {
- this.tid = tid;
- }
- public String getTname() {
- return tname;
- }
- public void setTname(String tname) {
- this.tname = tname;
- }
- public Integer getCid() {
- return cid;
- }
- public void setCid(Integer cid) {
- this.cid = cid;
- }
- }
3.编写DAO层(Service这里就省略了...)
3.0JDBC工具类
- package org.monday.util;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.Properties;
- /**
- * JDBC工具类
- *
- * @author Monday
- */
- public class JdbcUtil {
- private static Properties config = new Properties();
- /**
- * 加载驱动
- */
- static {
- try {
- InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
- config.load(in);
- Class.forName(config.getProperty("driver"));
- } catch (Exception e) {
- throw new ExceptionInInitializerError(e);
- }
- }
- /**
- * 获取连接
- */
- public static Connection getConnection() {
- try {
- return DriverManager.getConnection(config.getProperty("url"), config.getProperty("username"), config
- .getProperty("password"));
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * 释放资源
- */
- public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- rs = null;
- }
- if (pstmt != null) {
- try {
- pstmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- pstmt = null;
- }
- if (conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- conn = null;
- }
- }
- /**
- * 测试连接
- */
- public static void main(String[] args) {
- System.out.println(JdbcUtil.getConnection());
- System.out.println("ok");
- }
- }
jdbc.properties
- driver=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/linkage
- username=root
- password=root
3.1省份DAO
- package org.monday.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import org.monday.domain.Province;
- import org.monday.util.JdbcUtil;
- /**
- * 省份DAO
- *
- * @author Monday
- */
- public class ProvinceDao {
- public List<Province> findAllProvince() {
- List<Province> list = new ArrayList<Province>();
- Connection conn = null;
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try {
- conn = JdbcUtil.getConnection();
- String sql = "select pid,pname from province";
- pstmt = conn.prepareStatement(sql);
- rs = pstmt.executeQuery();
- while (rs.next()) {
- Province province = new Province();
- province.setPid(rs.getInt("pid"));
- province.setPname(rs.getString("pname"));
- list.add(province);
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- } finally {
- JdbcUtil.release(conn, pstmt, rs);
- }
- return list;
- }
- }
3.2城市DAO
- package org.monday.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import org.monday.domain.City;
- import org.monday.util.JdbcUtil;
- /**
- * 城市DAO
- *
- * @author Monday
- */
- public class CityDao {
- public List<City> findAllCity(Integer pid) {
- List<City> list = new ArrayList<City>();
- Connection conn = null;
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try {
- conn = JdbcUtil.getConnection();
- String sql = "select cid,cname,pid from city where pid=?";
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, pid);
- rs = pstmt.executeQuery();
- while (rs.next()) {
- City city = new City();
- city.setCid(rs.getInt("cid"));
- city.setCname(rs.getString("cname"));
- city.setPid(rs.getInt("pid"));
- list.add(city);
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- } finally {
- JdbcUtil.release(conn, pstmt, rs);
- }
- return list;
- }
- }
3.3乡镇DAO
- package org.monday.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import org.monday.domain.Town;
- import org.monday.util.JdbcUtil;
- /**
- * 乡镇DAO
- *
- * @author Monday
- */
- public class TownDao {
- public List<Town> findAllTown(Integer cid) {
- List<Town> list = new ArrayList<Town>();
- Connection conn = null;
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try {
- conn = JdbcUtil.getConnection();
- String sql = "select tid,tname,cid from town where cid=?";
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, cid);
- rs = pstmt.executeQuery();
- while (rs.next()) {
- Town town = new Town();
- town.setTid(rs.getInt("tid"));
- town.setTname(rs.getString("tname"));
- town.setCid(rs.getInt("cid"));
- list.add(town);
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- } finally {
- JdbcUtil.release(conn, pstmt, rs);
- }
- return list;
- }
- }
啰嗦了半天....终于写WEB层了...
4.Action
- package org.monday.web;
- import java.io.IOException;
- import java.util.List;
- import javax.servlet.http.HttpServletResponse;
- import net.sf.json.JSONArray;
- import org.apache.struts2.ServletActionContext;
- import org.monday.dao.CityDao;
- import org.monday.dao.ProvinceDao;
- import org.monday.dao.TownDao;
- import org.monday.domain.City;
- import org.monday.domain.Province;
- import org.monday.domain.Town;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * 处理三级联动的Action
- *
- * @author Monday
- */
- public class LinkageAction extends ActionSupport {
- private static final long serialVersionUID = -8658430555400755301L;
- private Integer pid;
- private Integer cid;
- private HttpServletResponse response = ServletActionContext.getResponse();
- /**
- * 获取省份
- */
- public String getProvince() {
- ProvinceDao provinceDao = new ProvinceDao();
- List<Province> provinceList = provinceDao.findAllProvince();
- JSONArray jsonArray = JSONArray.fromObject(provinceList);
- try {
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().print(jsonArray.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 获取城市
- */
- public String getCityByPid() {
- CityDao cityDao = new CityDao();
- List<City> cityList = cityDao.findAllCity(pid);
- JSONArray jsonArray = JSONArray.fromObject(cityList);
- try {
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().print(jsonArray.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 获取乡镇
- */
- public String getTownByCid() {
- TownDao townDao = new TownDao();
- List<Town> townList = townDao.findAllTown(cid);
- JSONArray jsonArray = JSONArray.fromObject(townList);
- try {
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().print(jsonArray.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- // -----------------
- public Integer getPid() {
- return pid;
- }
- public void setPid(Integer pid) {
- this.pid = pid;
- }
- public Integer getCid() {
- return cid;
- }
- public void setCid(Integer cid) {
- this.cid = cid;
- }
- }
strutx.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
- <struts>
- <!-- 设置开发模式 -->
- <constant name="struts.devMode" value="true" />
- <package name="default" namespace="" extends="struts-default">
- <action name="linkageAction_*" class="org.monday.web.LinkageAction" method="{1}">
- <result></result>
- </action>
- </package>
- </struts>
5.HTML
- <html>
- <head>
- <title>三级联动</title>
- <script language="JavaScript" src="jquery-1.4.2.js"></script>
- <script type="text/javascript" src="my.js"></script>
- </head>
- <body>
- <select id="province" name="province">
- <option value="">请选择</option>
- </select>
- <select id="city" name="city">
- <option value="">请选择</option>
- </select>
- <select id="town" name="town">
- <option value="">请选择</option>
- </select>
- </body>
- </html>
6.JS(重点来了)
- $(document).ready(function () {
- /* 获取省份 */
- $.post("linkageAction_getProvince.action", function (data) {
- var jsonObj = eval("(" + data + ")");
- for (var i = 0; i < jsonObj.length; i++) {
- var $option = $("<option></option>");
- $option.attr("value", jsonObj[i].pid);
- $option.text(jsonObj[i].pname);
- $("#province").append($option);
- }
- });
- /* 根据省份获取城市 */
- $("#province").change(function () {
- $.post("linkageAction_getCityByPid.action", {pid:$("#province").val()}, function (data) {
- /* 清空城市 */
- $("#city option[value!=' ']").remove();
- /* 清空乡镇 */
- $("#town option[value!=' ']").remove();
- var jsonObj = eval("(" + data + ")");
- for (var i = 0; i < jsonObj.length; i++) {
- var $option = $("<option></option>");
- $option.attr("value", jsonObj[i].cid);
- $option.text(jsonObj[i].cname);
- $("#city").append($option);
- }
- });
- });
- /* 根据城市获取乡镇 */
- $("#city").change(function () {
- $.post("linkageAction_getTownByCid", {cid:$("#city").val()}, function (data) {
- /* 清空乡镇 */
- $("#town option[value!='']").remove();
- var jsonObj = eval("(" + data + ")");
- for (var i = 0; i < jsonObj.length; i++) {
- var $option = $("<option></option>");
- $option.attr("value", jsonObj[i].tid);
- $option.text(jsonObj[i].tname);
- $("#town").append($option);
- }
- });
- });
- });