精华内容
下载资源
问答
  • JSP案例】无限级联|下拉列表

    千次阅读 2014-12-22 11:00:23
    本案例主要通过无限级联的数据结构来设计下拉列表 效果图: 1)设计无限级联数据库,并赋值 设计Id和ParentId字段,根类Id通过子类的ParentId来寻找,比如计算机是根类,他的子类是java和csharp。那java和...

    本案例主要通过无限级联的数据结构来设计下拉列表

    效果图:


    1)设计无限级联数据库,并赋值

    设计Id和ParentId字段,根类Id通过子类的ParentId来寻找,比如计算机是根类,他的子类是java和csharp。那java和csharp的parentId是计算机的Id。


    2)思路逻辑

    建立一个数据结构List<Hap<Object,List<Object>>>,List代表这张表,Object代表根类,List<Object>代表其子类。

     

    我们建立相应的bean Category类(对应数据表)

     

    在建立其对应的daoImpl类里面有找到其根类记录的方法和其子类记录的方法(参数就是ParentId,如果传入的是0就是找根类,传入的是其他数字就是找子类)

     

    业务逻辑层负责把根类和子类集合封装到List<Map<Category,List<Category>>>结构中

     

    Jsp得到集合后,先遍历List 得到map,然后通过keyset得到键值category对象,在通过category键值得到Map的值(集合)

     

    遍历子集合后,得到子类对象。

    3)JSP逻辑

    最外一层先包一层<select>标签

    for(遍历map){

    for(遍历map的key){

    在读取集合后得到键值,然后写<option>标签 value是category的id而内容是category的categoryName

    for(){

    在读取集合后得到键值,然后写<option>标签 value是category的id而内容是category的categoryName

    }

    }

    }

    4)这样select列表就做完了

    需要注意的问题

    虽然列表做好了,我们主要是为了通过下拉列表传值从数据库获取书籍表的数据,所以我们需要给页面传值

    下面是改善后的逻辑

    1)设置一个js事件(onChange),当列表的值发生改变后触发事件,事件负责重新跳转此页面传值

    2)通过String id=request.getParameter得到传的值,初次进入此页面时得到的id为null之后得到的id为option的value值

    3)我们原本for循环来输出的option标签,因为页面刷新后,option也会刷新,所以要给option设置selected。

    4)判断当前的id是否不为空,并且此Id和category当前的id是否一致,如果一致则显示有selected的字符串否则显示没有selected的字符串

    最后是本次练习的源码

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@page import="cn.mybookshop.bean.*"%>
    <%@page import="cn.mybookshop.biz.*"%>
    <%@page import="cn.mybookshop.biz.Impl.*"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <% 
    	String CurrId=request.getParameter("id");
    	if(CurrId!=null){
    		System.out.println(CurrId+"得到");
    	}
    %>
    <html>
    	<head>
    
    		<title>My JSP 'BookManager.jsp' starting page</title>
    		<script type="text/javascript">
    			function search(oSearch){
    				if(oSearch.value=="-1"){
    					alert("请输入你想查询的类别");
    					return;
    				}
    				
    				location.href="BookManager.jsp?id="+oSearch.value;
    			}
    		</script>
    	</head>
    	<body>
    	<div  style="margin-right: auto; text-align: center; margin-left: auto; margin-bottom: 0px; margin-top: 0px">
    	<select style="width: 165px; " onChange="search(this)">
    		<option value="-1">-----请选择-----</option>
    		<%
    			CategoryBiz cb=new CategoryBizImpl();
    			List<Map<Category,List<Category>>> list=cb.findAllCategory();
    			for(Map<Category,List<Category>> map:list){
    				Set<Category> set=map.keySet();
    				for(Category category:set){
    					String option="<option value='%d' %s>%s</option>";
    					if(null!=CurrId&&CurrId==String.valueOf(category.getId())){
    						out.println(String.format(option,category.getId(),"selected=selected",category.getCategoryName()));			
    					}else{
    						out.println(String.format(option,category.getId()," ",category.getCategoryName()));
    					}
    					List<Category> childList=map.get(category);
    					for(Category cate:childList){
    					if(null!=CurrId&&CurrId.equals(String.valueOf(cate.getId()))){
    						out.println(String.format(option,cate.getId(),"selected=selected","-----"+cate.getCategoryName()));			
    					}else{
    						out.println(String.format(option,cate.getId()," ","-----"+cate.getCategoryName()));
    					}
    				}
    				}
    			}
    			 %>
    		 </select>
    		 </div>
    	</body>
    </html>
    





    展开全文
  • 级联下拉列表 ajax实现(两种方式)

    千次阅读 2018-01-25 16:16:53
    案例:设置一个级联下拉列表,省市区,根据id进行查找,同属于同一个省的城市前两位id相同,属于同一个市的区前4位id相同 数据库数据如下(部分): 第一种方式:通过获取json对象,然后进行解析json对象...

    案例:设置一个级联下拉列表,省市区,根据id进行查找,同属于同一个省的城市前两位id相同,属于同一个市的区前4位id相同

    数据库数据如下(部分):


    第一种方式:通过获取json对象,然后进行解析json对象数组,动态创建下拉列表

    1:Dao代码如下:

    package com.oracle.dao;
    
    import java.util.List;
    
    import com.oracle.jdbc.util.Dao;
    import com.oracle.vo.City;
    
    public class CityDaoImpl implements CityDao {
       //第一种方式的方法,通过id+两位占位符获取 对象,id可以为空
    	@Override
    	public List<City> getCity(String id) {
    		String sql="select id,name from city where id like'"+id+"__'";
    		
    		return Dao.query(sql,City.class);
    	}
       //第二种方式的方法,获取对象存到list,循环取出 连接成html代码形式的字符串
    	@Override
    	public String getCities(String id) {
    		StringBuffer sb=new StringBuffer();
    		List<City>list=Dao.query("select id,name from city where id like'"+id+"__'",City.class);
    		for(City l:list){
    			sb.append("<option value='"+l.getId()+"'>"+l.getName()+"</option>");
    		}
    		return sb.toString();
    	}
    
    }
    
    2:在servlet中获取城市的id,返回该id下属的市或者区,servlet代码如下,调用dao中方法:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		//获取id值
    		String code=request.getParameter("code");
    		//设置编码
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/plain;charset=utf-8");
    		//利用工厂创建dao对象,并调用dao方法
    		CityDao dao=ServiceFactory.getObject(CityDaoImpl.class);
    		List<City>list=dao.getCity(code);
    		//通过jackson包的方法,将list对象转成jason对象,传回jsp中
    		ObjectMapper mapper=new ObjectMapper();		
    		String json=mapper.writeValueAsString(list);
    		
            response.getWriter().append(json);
    	}
    3.在jsp文件中编写ajax代码,实现传id返数据,代码如下
    <%@ 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>
    <script  src="js/jquery-1.11.1.js"></script>
    <script>
    $(function(){
    	//初始入口函数
    	//初始传入空字符串,自动查出id为两位的数据,都为省或直辖市
    	$.post("city.do",{code:""},function(data){
    		//循环插入在select中
    		for(var i=0;i<data.length;i++){
    			$("#province").append($("<option>").val(data[i].id).html(data[i].name));		
    		}
    		$("#province").change();
    	},"json")
    	
    	
    	//设置省change函数
    	$("#province").change(function(){
    		$.post("city.do",{code:$(this).val()},function(data){
    			$("#city").empty();//置空
    			for(var i=0;i<data.length;i++){
    				
    				$("#city").append($("<option>").val(data[i].id).html(data[i].name));		
    			}
    			$("#city").change();
    		},"json")
    		
    		
    	});
    	
    	
    	//设置市change函数
    	$("#city").change(function(){
    		$.post("city.do",{code:$(this).val()},function(data){
    			$("#area").empty();//置空
    			for(var i=0;i<data.length;i++){
    				
    				$("#area").append($("<option>").val(data[i].id).html(data[i].name));		
    			}
    		},"json")
    	});
    });
    </script>
    </head>
    <body>
    <select style="width:150px" id="province"></select>省
    <select style="width:150px" id="city"></select>市
    <select style="width:150px" id="area"></select>区
    </body>
    </html>

    第二种方式,通过Dao里的第二个方法,返回html代码形式的 list对象,直接设置在select的html中,可自动生成下拉菜单,级联更新子列表操作同上,不做过多解释

    1:servlet,代码如下:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		//取id
    		String id=request.getParameter("code");
    		//置编码
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/plain;charset=utf-8");
    		//调用dao对象的第二个方法,返回htm代码字符串
    		CityDao dao=ServiceFactory.getObject(CityDaoImpl.class);
    		String str=dao.getCities(id);
    		response.getWriter().append(str);
    	}

    2:jsp代码如下(只有script部分,其他部分同第一个方法相同):

    <script>
    $(function(){
    	
    	$.post("city2.do",{code:""},function(data){
    		$("#province").html(data);
    		$("#province").change();
    	})
    	
    	
    	$("#province").change(function(data){
    		$.post("city2.do",{code:$(this).val()},function(data){
    			$("#city").html(data);
    		})
    		$("#city").change();
    	});
    	$("#city").change(function(data){
    		$.post("city2.do",{code:$(this).val()},function(data){
    			$("#area").html(data);
    		})
    	});
    	
    });
    </script>

    以上两种方式都可以很好的实现级联下拉列表的功能,作为自己的学习记录,同时欢迎大家指出错误和可以更好改进的地方,大家一起共同进步~




    展开全文
  • index.jsp &amp;lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot; pageEncoding=&quot;UTF-8&quot;%&amp;gt; &amp;lt;!DOCTYPE ...

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script language="javascript" src="JS/AjaxRequest.js"></script>
    <script language="javascript">
    //获取省份和直辖市
    function getProvince(){
    	var loader=new net.AjaxRequest("ZoneServlet?action=getProvince&nocache="+new Date().getTime(),deal_getProvince,onerror,"GET");
    }
    function deal_getProvince(){
    	provinceArr=this.req.responseText.split(",");	//将获取的省份名称字符串分隔为数组
    	
    	for(i=0;i<provinceArr.length;i++){		//通过循环将数组中的省份名称添加到下拉列表中
    		//Option是 select 中的选择项,str1 是页面中看到的描述,而str2是这一项的值
    		document.getElementById("province").options[i]=new Option(provinceArr[i],provinceArr[i]);
    	}
    	if(provinceArr[0]!=""){
    		getCity(provinceArr[0]);	//获取市县
    	}
    }
    
    //在页面载入后显示默认的省份
    window.onload=function(){
    	 getProvince();		//获取省份和直辖市
    }
    /*************************************************************************************************************/
    //获取市县
    function getCity(selProvince){
    	var loader=new net.AjaxRequest("ZoneServlet?action=getCity&parProvince="+selProvince+"&nocache="+new Date().getTime(),deal_getCity,onerror,"GET");
    }
    function deal_getCity(){
    	cityArr=this.req.responseText.split(",");	//将获取的市县名称字符串分隔为数组
    	document.getElementById("city").length=0;	//清空下拉列表
    	for(i=0;i<cityArr.length;i++){		//通过循环将数组中的市县名称添加到下拉列表中
    		document.getElementById("city").options[i]=new Option(cityArr[i],cityArr[i]);
    	}
    }
    function onerror(){}		//错误处理函数
    </script>
      </head>
      
      <body style="font-size: 9pt;">
      请选择:
      		<!-- onchange 事件在用户改变输入域的内容时执行 JavaScript 代码 -->
    	  <select name="province" id="province" onChange="getCity(this.value)">
          </select>
          -
    	  <select name="city" id="city">
    	  </select>
      </body>
    </html>
    

    CityMap.jsp

    package com.wgh.tools;
    
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class CityMap {
    	   /**
         *  全国(省,直辖市,自治区,特别行政区)映射集合
         */
        public static Map<String,String[]> model=new LinkedHashMap();
        static{
            model.put("北京", new String[]{"北京"});
            model.put("上海", new String[]{"上海"});
            model.put("天津", new String[]{"天津"});
            model.put("重庆", new String[]{"重庆"});
            model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
            model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"});
            model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
            model.put("内蒙古", new String[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"});
            model.put("河北", new String[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"});
            model.put("河南", new String[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"});
            model.put("山东", new String[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"});
            model.put("山西", new String[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"});
            model.put("江苏", new String[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"});
            model.put("安徽", new String[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"});
            model.put("陕西", new String[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"});
            model.put("宁夏", new String[]{"银川","固原","中卫","石嘴山","吴忠"});
            model.put("甘肃", new String[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"});
            model.put("青海", new String[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"});
            model.put("湖北", new String[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"});
            model.put("湖南", new String[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"});
            model.put("浙江", new String[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"});
            model.put("江西", new String[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"});
            model.put("福建", new String[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"});
            model.put("贵州", new String[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"});
            model.put("四川", new String[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"});
            model.put("广东", new String[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"});
            model.put("广西", new String[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"});
            model.put("云南", new String[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"});
            model.put("海南", new String[]{"海口","三亚","儋州","琼山","通什","文昌"});
            model.put("新疆", new String[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"});
        }  
    }
    
    

    ZoneServlet.java

    package com.wgh.tools;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class ZoneServlet
     */
    @WebServlet("/ZoneServlet")
    public class ZoneServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public ZoneServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		String action=request.getParameter("action");		//获取action参数的值
    		if("getProvince".equals(action)){	//获取省份和直辖市信息
    			this.getProvince(request,response);
    		}else if("getCity".equals(action)){	//获取市县信息
    			this.getCity(request, response);
    		}
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    	public void getProvince(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		response.setCharacterEncoding("GBK");		//设置响应的编码方式
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
    		
    		String result="";
    		CityMap cityMap=new CityMap();//实例化保存省份信息的CityMap类的实例
    		Map<String,String[]> map= cityMap.model;//获取省份信息保存到Map中
    		Set<String> set=map.keySet();		//获取Map集合中的键,并以Set集合返回
    		Iterator it=set.iterator();
    		while(it.hasNext()){		//将获取的省份连接为一个以逗号分隔的字符串
    			result=result+it.next()+",";
    		}
    		result=result.substring(0, result.length()-1);	//去除最后一个逗号
    		
    		out.print(result);		//输出获取的省份字符串
    		out.flush();
    		out.close();
    	}
    	/**
    	 * 获取市县
    	 * @param request
    	 * @param response
    	 * @throws ServletException
    	 * @throws IOException
    	 */
    	public void getCity(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		response.setCharacterEncoding("GBK");	//设置响应的编码方式
    		response.setContentType("text/html");
    		PrintWriter out = response.getWriter();
    		
    		String result="";
    		String selProvince=request.getParameter("parProvince");	//获取选择的省份
    		selProvince=new String(selProvince.getBytes("ISO-8859-1"),"GBK");
    		CityMap cityMap=new CityMap();	//实例化保存省份信息的CityMap类的实例
    		Map<String,String[]> map=cityMap.model;	//获取省份信息保存到Map中
    		String[]arrCity= map.get(selProvince);	//获取指定键的值
    		for(int i=0;i<arrCity.length;i++){		//将获取的市县连接为一个以逗号分隔的字符串
    			result=result+arrCity[i]+",";
    		}
    		result=result.substring(0, result.length()-1);	//去除最后一个逗号
    		
    		out.print(result);								//输出获取的市县字符串
    		out.flush();
    		out.close();
    	}
    }
    
    

    Ajax重构:AjaxRequest.js

    var net = new Object(); // 定义一个全局变量net
    // 编写构造函数
    net.AjaxRequest = function(url, onload, onerror, method, params) {
    	this.req = null;
    	this.onload = onload;
    	this.onerror = (onerror) ? onerror : this.defaultError;
    	this.loadDate(url, method, params);
    }
    // 编写用于初始化XMLHttpRequest对象并指定处理函数,最后发送HTTP请求的方法
    net.AjaxRequest.prototype.loadDate = function(url, method, params) {
    	if (!method) {
    		method = "GET";
    	}
    	if (window.XMLHttpRequest) {
    		this.req = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
    		this.req = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    	if (this.req) {
    		try {
    			var loader = this;
    			this.req.onreadystatechange = function() {
    				net.AjaxRequest.onReadyState.call(loader);
    			}
    			this.req.open(method, url, true);// 建立对服务器的调用
    			if (method == "POST") {// 如果提交方式为POST
    				this.req.setRequestHeader("Content-Type",
    						"application/x-www-form-urlencoded"); // 设置请求头
    			}
    			this.req.send(params); // 发送请求
    		} catch (err) {
    			this.onerror.call(this);
    		}
    	}
    }
    
    // 重构回调函数
    net.AjaxRequest.onReadyState = function() {
    	var req = this.req;
    	var ready = req.readyState;
    	if (ready == 4) {// 请求完成
    		if (req.status == 200) {// 请求成功
    			this.onload.call(this);
    		} else {
    			this.onerror.call(this);
    		}
    	}
    }
    // 重构默认的错误处理函数
    net.AjaxRequest.prototype.defaultError = function() {
    	alert("错误数据\n\n回调状态:" + this.req.readyState + "\n状态: " + this.req.status);
    }
    
    展开全文
  • jsp出生日期三级级联下拉列表

    热门讨论 2011-04-07 01:20:04
    jsp出生日期三级级联下拉列表,今晚做的,呵呵!分享下!
  • AJAX_Servlet级联下拉列表 product.jsp UserServlet.java
  • 在使用JSP JavaScript过程中有很多的技巧与实现,那么如何构建二级级联下拉菜单呢,本文将会向你做一个源码上的介绍。
  • 利用 Ajax 技术可以在页面实现一个级联下拉列表

    JavaWeb——Ajax

    三、Ajax 常用方式

    1、级联下拉列表

    • 利用 Ajax 技术可以在页面实现一个级联下拉列表。例如选择省份和城市的一个级联下拉列表。

    1.1、创建一个 Map

    • 新建一个 Java 的 Map 类,用于存放全国省份和城市的名字,代码如下:
      package com.lyq.bean;
      import java.util.LinkedHashMap;
      import java.util.Map;
      
      public class CityMap {
          public static Map<String,String[]> model = new LinkedHashMap<>();
          static{
              model.put("北京", new String[]{"北京"});
              model.put("上海", new String[]{"上海"});
              model.put("天津", new String[]{"天津"});
              model.put("重庆", new String[]{"重庆"});
              model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
              model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"});
              model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
              model.put("内蒙古", new String[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"});
              model.put("河北", new String[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"});
              model.put("河南", new String[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"});
              model.put("山东", new String[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"});
              model.put("山西", new String[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"});
              model.put("江苏", new String[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"});
              model.put("安徽", new String[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"});
              model.put("陕西", new String[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"});
              model.put("宁夏", new String[]{"银川","固原","中卫","石嘴山","吴忠"});
              model.put("甘肃", new String[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"});
              model.put("青海", new String[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"});
              model.put("湖北", new String[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"});
              model.put("湖南", new String[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"});
              model.put("浙江", new String[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"});
              model.put("江西", new String[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"});
              model.put("福建", new String[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"});
              model.put("贵州", new String[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"});
              model.put("四川", new String[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"});
              model.put("广东", new String[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"});
              model.put("广西", new String[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"});
              model.put("云南", new String[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"});
              model.put("海南", new String[]{"海口","三亚","儋州","琼山","通什","文昌"});
              model.put("新疆", new String[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"});
          }
      }
      

    1.2、新建 Servlet

    • 新建一个 Servlet 用于处理页面的请求,代码如下:
      //@Software: IntelliJ IDEA
      // @Project: JavaWebProject1
      //@File:${NAME}
      //@Date:2019/12/15
      // Author:御承扬
      //E-mail:2923616405@qq.com
      package com.lyq.ServletSet;
      import com.lyq.bean.CityMap;
      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 java.io.IOException;
      import java.io.PrintWriter;
      import java.net.URLDecoder;
      import java.nio.charset.StandardCharsets;
      import java.util.Map;
      import java.util.Set;
      
      @WebServlet(name = "ZoneServlet", urlPatterns = "/ZoneServlet")
      public class ZoneServlet extends HttpServlet {
      
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String action = request.getParameter("action");
              if("getProvince".equals(action)){
                  this.getProvince(request,response);
              }else if("getCity".equals(action)){
                  this.getCity(request,response);
              }
          }
          public void getProvince(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
              response.setCharacterEncoding("UTF-8");
              StringBuilder result = new StringBuilder();
              Map<String, String[]> map = CityMap.model;
              Set<String> set = map.keySet();
              for (String s : set) {
                  result.append(s).append(",");
              }
              result = new StringBuilder(result.substring(0, result.length() - 1));
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              out.print(result);
              out.flush();
              out.close();
          }
          public void getCity(HttpServletRequest request,
                              HttpServletResponse response) throws ServletException, IOException{
              response.setCharacterEncoding("UTF-8");
              StringBuilder result= new StringBuilder();
              String selProvince=request.getParameter("parProvince");
              String province = URLDecoder.decode(selProvince, StandardCharsets.UTF_8);
              Map<String,String[]> map= CityMap.model;
              String[]arrCity= map.get(province);
              for (String s : arrCity) {
                  result.append(s).append(",");  // Stitching strings
              }
              result = new StringBuilder(result.substring(0, result.length() - 1));
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              out.print(result);
              out.flush();
              out.close();
          }
      }
      

    1.3、新建一个 JSP

    • 新建一个 JSP 页面,其代码如下:
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>级联下拉列表</title>
          <meta http-equiv="pragma" content="no-cache">
          <meta http-equiv="cache-control" content="no-cache">
          <meta http-equiv="expires" content="0">
          <script language="javascript" src="../JS/AjaxRequest.js"></script>
          <script language="javascript">
              //获取省份和直辖市
              function getProvince(){
                  var loader=new net.AjaxRequest("http://localhost:8080/JavaWebProject1_war_exploded/ZoneServlet?action=getProvince&nocache="
                      +new Date().getTime(),deal_getProvince,onerror,"GET");
              }
              function deal_getProvince(){
                  provinceArr=this.req.responseText.split(",");	//Separate the obtained province name strings into an array
      
                  for(i=0;i<provinceArr.length;i++){		//get province name by loop  and add to the drop-down list
                      document.getElementById("province").options[i]=new Option(provinceArr[i],provinceArr[i]);
                  }
                  if(provinceArr[0]!==""){
                      getCity(provinceArr[0]);	//get city name
                  }
              }
              window.onload=function(){
                  getProvince();		//get province name
              };
              /*************************************************************************************************************/
              function getCity(selProvince){
                  var province = encodeURI(encodeURI(selProvince));
      
                  var loader=new net.AjaxRequest("http://localhost:8080/JavaWebProject1_war_exploded/ZoneServlet?action=getCity&parProvince="
                      +province+"&nocache="+new Date().getTime(),deal_getCity,onerror,"GET");
              }
              function deal_getCity(){
                  cityArr=this.req.responseText.split(",");	//Separate the obtained city name string into an array
                  document.getElementById("city").length=0;	//clear up the drop-down list
                  for(i=0;i<cityArr.length;i++){		// get city name by loop and add to drop-down list
                      document.getElementById("city").options[i]=new Option(cityArr[i],cityArr[i]);
                  }
              }
              function onerror(){}		//a function to deal with error
          </script>
          <style type="text/css">
              body{
                  background: #bdd4e9;
                  align-items: center;
              }
          </style>
      </head>
      
      <body style="font-size: 14pt;">
      <center>
          请选择:
          <label for="province">省份:</label><select name="province" id="province" onChange="getCity(this.value)">
      </select>
          -
          <label for="city">城市:</label><select name="city" id="city">
      </select>
      </center>
      </body>
      </html>
      

    1.4、效果

    • 部署到 Tomcat 服务器运行,其效果如下:
      在这里插入图片描述
      在这里插入图片描述

    上一篇

    下一篇

    展开全文
  • 评论#re: JavaDB+JSP+AJAX实现的级联下拉菜单[未登录]2007-11-25 16:57haohao#re: JavaDB+JSP+AJAX实现的级联下拉菜单2007-11-30 10:41shaomin谢谢分享收下了回复更多评论#re: JavaDB+JSP+AJAX实现的级联下拉菜单...
  • Java web 级联下拉菜单的做法分享

    千次阅读 2018-12-03 14:27:59
    里面有一个添加商品信息和更新商品信息都需要用到级联下拉菜单。如果只是单纯的普通html就方便多了。于是想了两个方法。 方法一 Ajax+jquery //#“dalei”=大类型的下拉框。相对应xiaolei=小类型的下拉框 当你...
  • 一、 级联下拉列表(以行业大类和详细类为例) 主要实现思路: 主下拉列表(行业大类) 发生onchange事件时调用action查询次下拉列表 具体实现: 1. jsp页面脚本: function changeIndustry(industryId) { ...
  • 今天我将介绍自定义的bootstrap级联下拉菜单(你肯定用得到),主要应用场合有省市级关联菜单等等
  • 数据库需求分析:class(一级栏目信息):classId(自动编号),className(栏目名称)Nclass(二级栏目信息):NclassId(自动编号),NclassName(栏目名称),parentId(一级栏目id,与class表中的classId关联)级联菜单...
  • 使用ajax+struts2.0+jsp做的一个多下拉列表级联
  • Ajax实现级联下拉列表

    千次阅读 2016-12-13 22:34:12
    今天看了一个Ajax实现级联下拉列表的例子。在createAjax.js文件中。 var httprequest; function createAjax(url,callback) {  if (window.XMLHttpRequest) {  httprequest=new XMLHttpRequest();  }  else...
  • 网上级联菜单确有不少,单大多是直接写死到jsp页面中的,本代码是用mysql的数据库实现的,希望对大家有帮助!!!
  • 级联下拉列表 title > < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "expires" content = "0" > ...
  • 页面显示:area.jsp   &lt;div id="area"&gt; &lt;select id="area_first" onchange="ajax()"&gt; &lt;option value=-1&gt;--请选择--&lt;/...
  • 在实际项目中经常用到列表联动,比如省份、城市、区域三级联动,这里简要以二级联动来进行演示,思路很简单: 1、程序进入后首先调用获取省份方法getProvince,使用Ajax向服务器请求省份数据。 2、回调函数...
  • jsp+json+mySql 实现二级级联下拉菜单

    热门讨论 2010-07-27 18:53:19
    数据是从mySql数据库中动态读取,运行sql文件即可,经测试是没问题的……
  • 级联下拉列表笔记

    2014-12-25 17:25:21
    下拉框里的选项从数据库中...jsp: 客户类型: onchange="javascript:findCertType(this.value);"> 请选择客户类型 证件类型: 请先选择证件类型 javascript: //级联证件下拉框 findCertType = f
  • 三级级联下拉菜单实现(xml+js+struts)derekzhangv.at.hotmail.com好不容易实现的一个三级级联菜单,喜欢把复杂的问题简单化,所以从网上的一些方法中提取出一种相对清爽的方法-jsp页面里只多了2行代码.(不过多了两个...
  • 现在通过json和gson来实现完成一个级联下拉列表框(例如:省市联动) 1、前台jsp页面: 请选择 ${addressName} 2、前台js实现: /js/jquery-1.9.1.min.js"> $(doc
  • JSP 下拉框实现值联动实例

    万次阅读 2014-04-15 14:16:27
    下拉框值联动测试 var fjyt=[["NCR","DC","OTHER"], ["NCR","DC","OTHER"], ["NCR","DC","OTHER"], ["TZ"], ["SOP"] ]; ... var fjyt_des=[["NCR记录","尺寸记录","其他附件"], ...
  • } /** * 获取字段列表 * 2015年12月27日 * By hoge * @param model * @param rid * @return */ @RequestMapping(value = {"findfields"}) public @ResponseBody List findfields(Model model,String tablename) { ...
  • struct 级联下拉列表

    2012-11-27 21:30:23
    index.jsp: 使用s:doubleselect生成级联下拉列表框 使用s:doubleselect生成级联下拉列表框 籍贯" doubleList="#bs[top]" list="#bs.keySet()" doubleName="a" >
  • 我想做一个简单的ajax,jsp,xml三者结合的二级级联下拉框,就是把数据放到xml文件中 但我不知道如何读取xml中的数据,如何获取list,再按照选中的查找... 我已经做了ajax,jsp从数据库中读取数据。但不知如何...
  • 利用jsp+ajax+mysql实现的三个下拉列表级联,大家一起学习
  • 使用jsp脚本语言实现三级级联查询,效果,当你选择某一个省,相应显示该省的市,选择市,就相应弹出县
  • JSP+javascript打造二级级联下拉菜单: class(一级栏目信息):classId(自动编号),className(栏目名称), Nclass(二级栏目信息), NclassId(自动编号),NclassName(栏目名称),parentId(一级栏目id,与class...
  • 这是将《用Ajax实现多级联动下拉列表(无限级别,JSON传输数据,含全国地区数据库))》(原来是asp的)改写成JSP。下载包中包含一个org.json.jar,测试的时候,请将这个包加了应用服务器的lib目录中,原文地址:...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,128
精华内容 451
关键字:

jsp级联下拉列表