jdbc+servlet+ajax开发省市区三级联动
技术点:jdbc操作数据库,ajax提交,字符拦截器,三级联动
特点:局部刷新达到省市区三级联动,举一反三可以做商品分类等
宗旨:从实战中学习
博客讲解是按照两级联动,但下载的资源是三级联动含sql文件。
效果图:

首页核心代码:
- <%
- List<HashMap<String,Object>> maps = ConnectionUtil.findProvinces();
- pageContext.setAttribute("provinces", maps);
- %>
-
- <fieldset>
- <legend>省市区三级联动</legend>
- 省份:
- <select id="province" onchange="select_citys(this)">
- <option value="">-请选择-</option>
-
- <c:forEach var="pv" items="${provinces}">
- <option value="${pv.id}">${pv.name}</option>
- </c:forEach>
- </select>
- 城市:
- <select id="city" onchange="select_areas(this)">
- <option value="">-请选择-</option>
- </select>
- 区域:
- <select id="area">
- <option value="">-请选择-</option>
- </select>
- </fieldset>
ajax代码:
- function select_citys(obj){
- var provinceId = $(obj).val();
- if(!provinceId)return; // 声明变量就要判断是否为null
- $.ajax({
- type:"post",//请求方式get/post
- url:"${ctx}/CityServlet",//请求对应的地址
- data:{"provinceId":provinceId},//往服务器传递的参数,
- success:function(data){//服务器交互成功调用的回调函数,data就是服务器端传递出来的数据
- var jdata = data.trim(); // 去前后空格
- if(jdata=="fail"){
- alert("查询失败!");
- }else{
- var jsonData = eval(jdata);//将字符串的json对象转换成json
- $("#area").html("<option>-请选择-</option>");
- append_template(jsonData,"city");
- }
- }
- });
- };
-
后台处理核心代码:
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- PrintWriter out=response.getWriter();
-
- String pid = request.getParameter("provinceId");
- if (pid != null && !pid.equals("")) {
- int provinceId = Integer.parseInt(pid);
- List<HashMap<String, Object>> citys = ConnectionUtil
- .findCitys(provinceId);
- try {
-
- out.print(JSONUtil.serialize(citys));
- } catch (JSONException e) {
- e.printStackTrace();
- }
- } else {
-
- out.print("fail");
- }
- }
数据库操作:
- package com.ajax.connection;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
-
- public class ConnectionUtil {
-
- private static String url = "jdbc:mysql:///test";
- private static String username = "root";
- private static String password = "root";
-
- public static Connection getConnection(){
- Connection connection = null;
- try{
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection(url,username,password);
- return connection;
- }catch(Exception ex){
- return null;
- }
- }
-
- public static List<HashMap<String, Object>> findProvinces(){
- Connection connection = null;
- Statement statement = null;
- ResultSet rs = null;
- List<HashMap<String, Object>> maps = null;
- try{
- String sql = "SELECT id,name FROM tm_province order by sort asc";
- connection = getConnection();
- statement = connection.createStatement();
- rs = statement.executeQuery(sql);
- maps = new ArrayList<HashMap<String,Object>>();
- HashMap<String, Object> map = null;
- while(rs.next()){
- map = new HashMap<String, Object>();
- map.put("id", rs.getInt("id"));
- map.put("name", rs.getString("name"));
- maps.add(map);
- }
- return maps;
- }catch(SQLException sql){
- sql.printStackTrace();
- return null;
- }finally{
- try{
- if(rs!=null)rs.close();
- if(statement!=null)statement.close();
- if(connection!=null)connection.close();
- }catch(SQLException sql){
- sql.printStackTrace();
- }
- }
- }
-
-
-
- }
字符拦截器:
- package com.ajax.filter;
-
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- public class CharacterFilter implements Filter {
-
- private FilterConfig config;
-
- public void doFilter(ServletRequest req, ServletResponse resp,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) resp;
-
- String encoding = config.getInitParameter("encoding");
-
- if (encoding != null) {
-
- response.setContentType("text/html ;charset=" + encoding);
-
- request.setCharacterEncoding(encoding);
-
- response.setCharacterEncoding(encoding);
- }
-
- chain.doFilter(request, response);
- }
-
- public void init(FilterConfig config) throws ServletException {
- this.config = config;
- }
- public void destroy() {
- }
- }
ajax省市区三级联动
原文:http://www.cnblogs.com/Logo-TPM/p/6206172.html