利用jquery,ajax和sertvlet实现省市菜单的联动

今天要实现的效果:

 

1在eclipse中创建一个动态的web项目

 

2使用jdbc连接mysql数据库,可以用sqyog进行图形化显示,可以自己封装一些常用的增删改查的方法

先创建一个java类在里面利用jdbc连接数据库

代码如下:

package BaseDAO;
import bean.she;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Base<e> {
    private static String class1 = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/xuexi?characterEncoding=utf8";
    private static String username = "root";
    private static String userpwd = "123456";
    private static Connection conn = null;
    private static Statement stmt = null;
    protected static ResultSet rs= null;

    static {
        try{
            Class.forName(class1);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public void lianjie() throws SQLException {
        conn =  DriverManager.getConnection(url,username,userpwd);
        System.out.println("====连接成功====");
    }
    public void chuangjian() throws SQLException {
        stmt = conn.createStatement();
        System.out.println("====创捷成功====");
    }

    
    //    更新
    public void zhexing(String sql) throws SQLException {
        lianjie();
        chuangjian();
        stmt.executeUpdate(sql);
        System.out.println("=====sql===="+sql);
        qingchu();
    }


    public List<e> chaxun(String sql) throws SQLException {
        lianjie();
        chuangjian();
        rs = stmt.executeQuery(sql);
        System.out.println("===============chaxunhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh=========="+sql);
        List<e> list =  new ArrayList<e>();
        System.out.println("===============chaxun222==========");
        yunxing(list);
        System.out.println("===============yunxing==========");
        qingchu();
        System.out.println("======查询我完毕=====");
        System.out.println("======listsize111111====="+list.size());
        return list;
    }


    public void qingchu (){
        if (rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            rs=null;
        }
        if (stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            stmt=null;
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            conn=null;
        }
    }


    public void yunxing(List<e> list) throws SQLException {

    }
	
}

和dao层中增删改查的方法

package BaseDAO;

import java.sql.SQLException;
import java.util.List;
import bean.she;
public class sheDAO extends Base<she>{
	public List<she> fandall()throws SQLException {
    	StringBuffer sql = new StringBuffer("SELECT * FROM she");
        return super.chaxun(sql.toString());
    }
    public List<she> fandalltiaojian(StringBuffer sql)throws SQLException {
        return super.chaxun(sql.toString());
    }
    public void yunxing(List<she> list)  {
        try{
            while (rs.next()) {
                String sheid = rs.getString("sheid");
                String shename = rs.getString("shename");
                she hh = new she(sheid,shename);
                list.add(hh);
            }
        }
        catch (SQLException e){
            e.printStackTrace();
        }

    }
}

在创建一个实体bean

package bean;

public class she {
	private String sheid;
	private String shename;
	public String getSheid() {
		return sheid;
	}
	public void setSheid(String sheid) {
		this.sheid = sheid;
	}
	public String getShename() {
		return shename;
	}
	public void setShename(String shename) {
		this.shename = shename;
	}
	public she(String sheid, String shename) {
		super();
		this.sheid = sheid;
		this.shename = shename;
	}
	
	@Override
	public String toString() {
		return "she [sheid=" + sheid + ", shename=" + shename + "]";
	}
	
}

注意他们之间用泛型。base<she>:就是base里的e随着shedao实际继承传入的实体bean改变而改变。

3创建service层,创建实际操作的业务层和逻辑层

package sheservice;

import java.sql.SQLException;
import java.util.List;

import BaseDAO.sheDAO;
import bean.she;

public class sheservice {
	public List<she> fand1() throws SQLException{
		return new sheDAO().fandall();
	}
}

这里因为我们的业务较为简单所以service层就一个函数

4创建servlet层

创建与前端进行数据交互的对应的servlet:

package sheservlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.she;
import sheservice.sheservice;

/**
 * Servlet implementation class shefandservlet
 */
@WebServlet("/shefandservlet.do")
public class shefandservlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("===============servletchengg=========================");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		System.out.println("----------");
		List<she> list = null;
		try {
			list = new sheservice().fand1();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("========================servlet==========================="+list.size());
		StringBuffer str = new StringBuffer();
		System.out.println("======str===="+str.toString());
		str.append("[");
		System.out.println("======str===="+str.toString());
		for(int i = 0 ; i<list.size();i++) {
			if(i!=0) {
				str.append(",");
			}
			str.append("{");
			str.append("\"sheid\"");
			str.append(":");
			str.append("\""+list.get(i).getSheid()+"\"");
			str.append(",");
			str.append("\"shename\"");
			str.append(":");
			str.append("\""+list.get(i).getShename()+"\"");
			str.append("}");
		}
		str.append("]");
		
		System.out.println("======str===="+str.toString());
		response.getWriter().print(str.toString());
		
	}
	

}

这里运用了将list数据转化为json字符串的方式,通过response.getriter().print()的方法传到前端的jsp中

5创建jsp,和引入jquery,创建ajax异步请求

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js" ></script>
<script type="text/javascript">
$(function(){
	alert("======56677878===");
	$.ajax({
		 type:"get",
         url:"shefandservlet.do",
         dataType:"text",
         data:{"a":1},
         cache:false,
         success:function (data){
        	eval("msg="+data);
       	   alert("======56677878==="+msg);
       	  var str="<option value='-1'>==请选择省===</option>";
       	  for(var i =0;i<msg.length;i++){
       		  str+="<option value='"+msg[i].sheid+"'>"+msg[i].shename+"</option>";
       	  }
       	  alert("======32==="+str)
       	  $("#s1").html(str);
         	}
         
	})
	 $("#s1").on("change",function(){
		   var  sheid=$("#s1").val();
		   if(sheid!=-1){
			   $.ajax({
				   type:"get",
				   url:"city.do",
				   cache:false,
				   dataType:"text",
				   data:{"sheid":sheid},
				   success:function(data){
					   eval("citys="+data);
					   alert("======citys123==="+citys);
					   var str="<option value='-1'>==请选择市县===</option>";
					   for(var i=0;i<citys.length;i++){
						   str+="<option value='"+citys[i].cityid+"'>"+citys[i].cityname+"</option>";
					   }
					   alert("======str123==="+str);
					   $("#s2").css("display","block");
					   $("#s2").html(str);
				   }
			   }); 
		   }else{
			   $("#s2").css("display","none");
		   }
		   
	   })
	   
})
	
	
	
	





</script>
<body>
<div id="d1">
	<select id="s1">
	
	
	
	</select>

	<select id="s2" style="display: none;">
	
	
	
	</select>






</div>
</body>
</html>

这里我通过线上引入jquery包。$.ajax通过get发送请求到servlet,servlet通过调用service中的方法叨叨一个list集合,在吧list集合转化成json字符串,发送到ajax异步中,异步请求在把得到的json字符串通过eval解析成数组。再拼接成option语句,再通过$("#s2").html(str);插入到select中,通过网页加载出来

同理市的信息大概也是这样,只是要通过ajax中data传到servlet一个省的id,servlet通过接受这id去数据库中找到这个省对应的市的信息。在通过同样的方式传到ajax的回调函数进行处理。在插入到对应的select中,显示出来。

6总结

最后今天的分享就到这里了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值