使用Ajax和Jquery配合数据库实现下拉框的二级联动

首先我们需要先建立好数据库,将一些数据插入进去

需要两张表:

province:省份表

city: 城市表

如图:

然后再在java中建立相关的实体类与之对应

再然后,我们就能开始做jdbc的操作了

public class ConnectionFactory { 
 private static String driver; 
 private static String url; 
 private static String user; 
 private static String password; 
 static { 
  Properties prop = new Properties(); 
  //读取文件 
   
  try { 
   InputStream in = ConnectionFactory.class.getResourceAsStream("./jdbc.properties"); 
    
   prop.load(in); 
   driver = prop.getProperty("jdbc.driver"); 
   url = prop.getProperty("jdbc.url"); 
   user = prop.getProperty("jdbc.user"); 
   password = prop.getProperty("jdbc.password"); 
  } catch (IOException e) { 
   e.printStackTrace(); 
  } 
   
 } 
  
 /** 
  * 获取连接对象 
  * @return 
  */ 
 public static Connection getConnection(){ 
  Connection conn = null; 
   
  try { 
   Class.forName(driver); 
   conn = DriverManager.getConnection(url, user, password); 
    
  } catch (Exception e) { 
   throw new RuntimeException(e); 
  } 
   
  return conn; 
 } 
  
 /** 
  * 关闭资源 
  * @param conn 
  * @param pstmt 
  * @param stmt 
  * @param rs 
  */ 
 public static void close(Connection conn,PreparedStatement pstmt,Statement stmt,ResultSet rs){ 
    
   try { 
    if (conn != null) { 
     conn.close(); 
    } 
     
    if (pstmt != null) { 
     pstmt.close(); 
    } 
     
    if (stmt != null) { 
     stmt.close(); 
    } 
     
    if (rs != null) { 
     rs.close(); 
    } 
   } catch (SQLException e) { 
    throw new RuntimeException(e); 
   } 
   
 } 

首先我们可以在页面加载的时候获取所有省份的信息,SQL语句如下

Connection conn = null; 
 PreparedStatement pstmt = null; 
 Province province2 = null; 
  
 @Override 
 public ArrayList<Province> findAllPro() { 
  ResultSet rs = null; 
  ArrayList<Province> pros = null; 
  try { 
   String sql = "select id,place from province"; 
   conn = ConnectionFactory.getConnection(); 
   pstmt = conn.prepareStatement(sql); 
   pros = new ArrayList<Province>(); 
    
   rs = pstmt.executeQuery(); 
    
   while(rs.next()){ 
    Province province = new Province(); 
    province.setId(rs.getInt(1)); 
    province.setPlace(rs.getString(2)); 
    pros.add(province); 
   } 
    
  } catch (SQLException e) { 
   throw new RuntimeException(e); 
  } 
   
  return pros; 
 } 

将查到的数据放到后台,建立一个SelectedServlet类,用于接收查询到的所有省份的信息

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/30.html