• javaweb+mysql+c3p0ajax实现三级联动


    1.首先要导入jar文件:

    c3p0-0.9.5.1.jar
    commons-beanutils-1.7.0.jar
    commons-collections-3.2.jar
    commons-dbutils-1.6.jar
    commons-lang-2.4.jar
    commons-logging-1.0.4.jar
    ezmorph-1.0.3.jar
    fastjson-1.1.40.jar
    jackson-all-1.7.5.jar
    json-lib-2.2.3-jdk15.jar
    mchange-commons-java-0.2.10.jar
    mysql-connector-java-5.1.30-bin.jar

    2.c3p0配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <c3p0-config>
     3   <default-config>
     4 
     5     <property name="checkoutTimeout">30000</property>
     6     <property name="idleConnectionTestPeriod">30</property>
     7     <property name="initialPoolSize">10</property>
     8     <property name="maxIdleTime">30</property>
     9     <property name="maxPoolSize">100</property>
    10     <property name="minPoolSize">10</property>
    11     <property name="maxStatements">200</property>
    12     
    13     <!-- 驱动程序 -->
    14     <property name="driverClass">com.mysql.jdbc.Driver</property>
    15     <!-- 数据库连接url地址 -->
    16     <property name="jdbcUrl">jdbc:mysql://localhost:3306/day02</property>
    17     <!-- 用户名 -->
    18     <property name="user">****</property>
    19     <!-- 密码 -->
    20     <property name="password">****</property>
    21 
    22  
    23   </default-config>
    24 </c3p0-config>
    25 
    26 <!-- <?xml version="1.0" encoding="UTF-8"?>
    27 <c3p0-config>
    28   <named-config > 
    29     <property name="acquireIncrement">5</property>
    30     <property name="initialPoolSize">3</property>
    31     <property name="minPoolSize">1</property>
    32     <property name="maxPoolSize">10</property>
    33     <property name="maxStatements">0</property> 
    34     <property name="user">root</property>
    35     <property name="password">root</property>
    36     ?useUnicode=true&characterEncoding=UTF-8
    37     <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    38     <property name="driverClass">com.mysql.jdbc.Driver</property>
    39   </named-config>
    40 </c3p0-config> -->
    41 
    42 
    43     

    3..要建三张表,省市区分别一张

    3.写对应的实体类

    1 public class Province {
    2 
    3     private Integer provinceId;
    4     private String provinceName;
    5 
    6       .....省略get和set代码      
    7 }
    1 public class City {
    2 
    3     private Integer cityId;
    4     private String cityName;
    5       
    6    .....省略get和set方法  
    7 }
    1 public class Area {
    2 
    3     private Integer areaId;
    4     private String areaName;
    5     ...省略set和get方法
    6 }

    4.Util包下的DBManager

     1 public class DBManager {
     2 
     3         private static ComboPooledDataSource cpds=new ComboPooledDataSource();
     4         
     5         //获取数据库资源
     6         public static ComboPooledDataSource getDateResource(){
     7             return cpds;
     8         }
     9         
    10         //返回连接对象
    11         public static Connection getConn() throws SQLException{
    12             return cpds.getConnection();
    13         }
    14         
    15         //释放资源
    16         public static void release(Connection conn){
    17             DbUtils.closeQuietly(conn);
    18         }
    19         
    20         
    21 }

    5.dao层

     1 public class BaseDao{
     2 
     3 private static final QueryRunner runner = new QueryRunner();
     4     
     5     public <T> List<T> getForList(String sql,Class<T> clazz,Object ...args) throws SQLException{
     6         
     7         List<T> list  = null;
     8         
     9         Connection conn = null;
    10         
    11         try {
    12             conn = DBManager.getConn();
    13             list = runner.query(conn, sql,new BeanListHandler<T>(clazz),args);
    14         } catch (Exception e) {
    15             throw new RuntimeException(e);
    16         }finally{
    17             DbUtils.close(conn);
    18         }
    19         
    20         return list;
    21         
    22         
    23     }

    6.前台页面 index.jsp

    <%
        response.sendRedirect("provinceServlet?method=listProvince");
        
    %>

    访问顺序是--->index.jsp----->provinceServlet?method=listProvince------>provice.jsp

    7.provice.jsp(包含ajax代码)

      1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
      3 
      4 
      5 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      6 <html>
      7   <head>
      8     
      9     
     10     <title>三级联动页面</title>
     11     
     12     <meta http-equiv="pragma" content="no-cache">
     13     <meta http-equiv="cache-control" content="no-cache">
     14     <meta http-equiv="expires" content="0">    
     15     <!-- 
     16         1.获取#province,添加change函数
     17         2.使#province只保留一个option子节点
     18         3.获取province下来菜单选择的值,若选择的值为“”(请选择省份),此时不需要发送ajax请求
     19         4.若值不为“”,说明的确是province发生了改变,发送ajax请求
     20         4.1  url:provinceServlet?method=
     21         4.2  args: 
     22         5.返回的是一个json数组
     23         6.遍历,创建<option value="provinceId">provinceName</option>
     24         并把新创建的option节点加为#city的子节点
     25      -->
     26     <script type="text/javascript" src="js/jquery-2.1.4.js"></script>
     27     <script type="text/javascript">
     28         $(function(){
     29         //第二级
     30              $("#province").change(function(){
     31             
     32                 $("#city option:not(:first)").remove();
     33                 var province = $(this).val();
     34                     //alert(province);
     35                 
     36                     var url = "provinceServlet?method=listCity";
     37                     var args = {"provinceId":province/* ,"time":new Date() */};
     38                     
     39                     $.getJSON(url, args, function(data){
     40                     //alert("11111");
     41                     
     42                         for(var i = 0;i < data.length; i++){
     43                     
     44                             var cityId = data[i].cityId;
     45                             var cityName = data[i].cityName;
     46                             
     47                             $("#city").append("<option value='"+ cityId  + "'>"+cityName+"</option>")
     48                             
     49                         }
     50                     
     51                     
     52                     
     53                     });
     54                         
     55                     
     56                     
     57                     
     58                 }
     59             );
     60          
     61          
     62          //第三极
     63          $("#city").change(function(){
     64             
     65                 $("#area option:not(:first)").remove();
     66                 var city = $(this).val();
     67                     //alert(province);
     68                 
     69                     var url = "provinceServlet?method=listArea";
     70                     var args = {"cityId":city,"time":new Date()}; //这里写一个时间戳 每次点击时,时间戳都不一样,浏览器就认为是新的图片,然后就发送请求了。
     71                     
     72                     $.getJSON(url, args, function(data){
     73                     //alert("11111");
     74                     
     75                         for(var i = 0;i < data.length; i++){
     76                     
     77                             var areaId = data[i].areaId;
     78                             var areaName = data[i].areaName;
     79                             
     80                             $("#area").append("<option value='"+ areaId  + "'>"+areaName+"</option>")
     81                             
     82                         }
     83                     
     84                     
     85                     
     86                     });
     87                         
     88                     
     89                     
     90                     
     91                 }
     92             );
     93         });
     94     
     95     </script>
     96 
     97   </head>
     98   
     99   <body>
    100            省份:<select id="province">
    101             <option>请选择省份</option>
    102             <c:forEach items="${provinces}" var="province">
    103                 <option value="${province.provinceId}">${province.provinceName}</option>
    104             </c:forEach>
    105                 
    106             </select>
    107             城市:<select id="city">
    108                     <option>请选择城市</option>
    109                 </select>
    110             区域:<select id="area">
    111                     <option>请选择区域</option>
    112                 </select>
    113   </body>
    114 </html>

    8.proviceServlet

     1 package three.controller;
     2 
     3 import java.io.IOException;
     4 import java.lang.reflect.Method;
     5 import java.sql.SQLException;
     6 import java.util.List;
     7 
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 import org.codehaus.jackson.map.ObjectMapper;
    14 
    15 import three.dao.BaseDao;
    16 import three.domain.Area;
    17 import three.domain.City;
    18 import three.domain.Province;
    19 
    20 public class provinceServlet extends HttpServlet {
    21 
    22     
    23     public void doGet(HttpServletRequest request, HttpServletResponse response)
    24             throws ServletException, IOException {
    25         
    26         request.setCharacterEncoding("UTF-8");
    27         response.setContentType("text/html;charset=UTF-8");
    28         
    29         
    30 
    31         String methodName = request.getParameter("method");
    32         
    33         try {
    34             Method method = getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
    35             method.invoke(this, request,response);
    36         } catch (Exception e) {
    37             e.printStackTrace();
    38         } 
    39         
    40     }
    41 
    42     private BaseDao  baseDao = new BaseDao();
    43     public void listProvince(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException{
    44         
    45         String sql = "SELECT provinceid,provincename FROM province;";
    46         List<Province> provinces = baseDao.getForList(sql, Province.class);
    47         request.setAttribute("provinces", provinces);
    48         
    49         request.getRequestDispatcher("/province.jsp").forward(request, response);
    50         
    51     
    52     }
    53 
    54 
    55     public void listCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException{
    56         
    57         String provinceId = request.getParameter("provinceId");
    58         String sql = "select cityid,cityname from city c where c.cityid = ?";
    59         
    60         List<City> cities = baseDao.getForList(sql, City.class, Integer.parseInt(provinceId));
    61         
    62         System.out.println(cities+"===========");
    63         
    64         ObjectMapper mapper = new ObjectMapper();
    65         String result = mapper.writeValueAsString(cities);
    66         System.out.println(result);
    67         
    68         response.setContentType("text/javascript");
    69         response.getWriter().print(result);
    70         
    71         
    72     }
    73 
    74 public void listArea(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException{
    75     
    76     String cityId = request.getParameter("cityId");
    77     String sql = "select areaid,areaname from area a where a.areaid = ?";
    78     
    79     List<Area> areas = baseDao.getForList(sql, Area.class, Integer.parseInt(cityId));
    80     
    81     System.out.println(areas+"===========");
    82     
    83     ObjectMapper mapper = new ObjectMapper();
    84     String result = mapper.writeValueAsString(areas);
    85     System.out.println(result);
    86     
    87     response.setContentType("text/javascript");
    88     response.getWriter().print(result);
    89     
    90     
    91 }
    92 
    93     public void doPost(HttpServletRequest request, HttpServletResponse response)
    94             throws ServletException, IOException {
    95 
    96         doGet(request,response);
    97     }
    98 
    99 }
  • 相关阅读:
    Git
    Entropy, relative entropy and mutual information
    2021.5.3 团队冲刺第六天
    2021.5.2 团队冲刺第五天
    2021.5.1 团队冲刺第四天
    2021.4.30 团队冲刺第三天
    2021.4.29 团队冲刺第二天
    2021.4.28 团队冲刺第一天
    2021.4.27
    2021.4.26
  • 原文地址:https://www.cnblogs.com/zx-n/p/5278040.html
Copyright © 2020-2023  润新知