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();
- // 获取ajax请求发送过来的省份id参数
- String pid = request.getParameter("provinceId");
- if (pid != null && !pid.equals("")) {// 有变量就要进行空判断
- int provinceId = Integer.parseInt(pid);// 因为前端都是传String;所以要转换
- List<HashMap<String, Object>> citys = ConnectionUtil
- .findCitys(provinceId);
- try {
- // 将集合对象转换成json格式---List---JsonArr字符串[{},{},{}]
- 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;
- /**
- * 数据库链接,查询类
- * 对jdbc操作数据库不懂的可以参考:http://blog.csdn.net/qq_19558705/article/details/49947317
- * 以下内容就不做过多的注释了
- * 实际业务会采用连接池的方式,这只做学习使用
- * @author Administrator
- *
- */
- 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;
- /**
- * 如果不清楚字符拦截器可以参考:http://blog.csdn.net/qq_19558705/article/details/49962153
- * @author Administrator
- *
- */
- 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;
- // 从web.xml文件中获取encoding对应的init-param中的param-value
- String encoding = config.getInitParameter("encoding");
- // 只要定义了变量;就要判断是否为空;不然会报空指针异常
- if (encoding != null) {
- // 指明内容请求格式的字符编码集
- response.setContentType("text/html ;charset=" + encoding);
- // 请求时规范字符编码格式
- request.setCharacterEncoding(encoding);
- // 指明输出的格式字符编码集
- response.setCharacterEncoding(encoding);
- }
- // 进入下一个拦截器
- chain.doFilter(request, response);
- }
- // FilterConfig 是拦截器的全局变量
- public void init(FilterConfig config) throws ServletException {
- this.config = config;
- }
- public void destroy() {
- }
- }