JQuery

JQury 入门

1.什么是jQuery
它是一个轻量级的javascript类库

2.jQuery优点

  • 总是面向集合
  • 多行操作集于一行

1 使用JQuery 先导入.js文件
2 然后在 导入js库( < script type=“text/javascript” src="">)
在这里插入图片描述
3 $(fn)做为程序入口


$ (fn)、$(document).ready(fn)与window.onload的区别?

<script type="text/javascript">
    /* 1.$(fn)、$(document).ready(fn)与window.onload的区别? */
    window.onload = function(){
    	alert("hello jquery3");
    }  
    $(function(){
    	alert("hello,jquery1");
    }) 
    
     $(document).ready(function(){
    	alert("hello jquery2");
    }) 
    /* 结论:$(fn)、$(document).ready(fn)是等价的,那个代码在前,那个代码先执行
         jsp的dom树结构加载完毕即刻调用方法      
          window.onload 最后执行
          jsp的dom加载完,css、js等静态资源加载完毕执行
    */ 
 </script>

选择器

<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
 
   $(function(){
	 // 标签选择器
	      // 利用 a 标签获取jquery的实例
	  /*  $("a").click(function(){
		   alert("我是谁");
	   }) */
	  
	 // ID选择器  利用id=3获取jquery的实例
	     /* $("#a3").click(function(){
	    	 alert("与你无瓜");
	     }); */
	 
	 // class 选择器
	   /*   $(".c1").click(function(){
	    	 alert("与你无瓜");
	     }); */
	 
	 // 包含选择器
	   /* $("p a").click(function() {
		   alert("与你无瓜");
	    }); */
	 // 组合选择器
	 /*  $("a,span,button").click(function() {
		  alert("与你无瓜");
	    }); */
	    
	 // 第二个参数(在div标签内部寻找a标签,然后在加事件)
	 // 如果第二个参数没有填 那么默认是document(整个文档)对象
	 $("a","div").click(function(){
		 alert("与你无瓜");
	 });
   });
  
</script>
</head>
<body>
	<p>
		<a id="a1" class="c1" href="#">点我1</a>
	</p>
	<p>
		<a id="a2" class="c2" href="#">点我2</a>
	</p>
	<p>
		<a id="a3" class="c3" href="#">点我3</a>
	</p>
	<div>
		<a id="a4" class="c1" href="#">点我4</a>
	</div>
	<div>
		<p>
			<a id="a5" class="c1" href="#">点我5</a>
		</p>
	</div>
	<span>来啊</span>
	<button>照做啊</button>

</body>
</html>

追加(append、appendTo),jquery 转换 js 、js 转jquery

<%@ 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">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		// 在 id=selId1的select标签的jquery实例上追加"<option value='1'>"的html jquery的实例
		$(":input[name='name1']").click(function() {
			$("#selId1").append("<option value='1'>湖南省</option>")
		});

		$(":input[name='name2']").click(function() {
			// 将 "<option value='1'>长沙市</option>" 的html  jquery实例追加到id=selId2的标签jquery实例中
			$("<option value='1'>长沙市</option>").appendTo("#selId2");

		});

		/* var $h1 = $("#h1");
		alert($h1.val());
		// jquery对象转js对象
		// var h1Node = $h1.get(0)  // 集合 
		var h1Node = $h1[0];        // 数组
		alert(h1Node.value); */
		
		var h2Node = document.getElementById("h2");
		alert(h2Node.value);
		// js对象转jquery对象
		var $h2Node = $(h2Node);
		alert($h2Node.val());
		
		
	});
</script>
</head>
<body>
	<select id="selId1">
		<option value="-1">---请选择---</option>
	</select>
	<select id="selId2">
		<option value="-1">---请选择---</option>
	</select>
	<input name="name1" value="add1" type="button">
	<input name="name2" value="add2" type="button">

	<input type="hidden" id="h1" value="h1">
	<input type="hidden" id="h2" value="h2">
	<input type="hidden" id="h3" value="h3">
</body>
</html>

this 使用

this

<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<script type="text/javascript">

   $(function(){   // 程序入口
	   $(":input").click(function(){
		   // 指的是事件源
		   alert(this.value);
		   // 获取所有a标签调取 each 方法
		   $("a").each(function(){
			   // 指的是当前元素
			   alert($(this).html());
		   });
	   });
   });

</script>
<body>
	<p>
		<a id="a1" class="c1" href="#">点我1</a>
	</p>
	<p>
		<a id="a2" class="c2" href="#">点我2</a>
	</p>
	<p>
		<a id="a3" class="c3" href="#">点我3</a>
	</p>
	<div>
		<a id="a4" class="c1" href="#">点我4</a>
	</div>
	<div>
		<p>
			<a id="a5" class="c1" href="#">点我5</a>
		</p>
	</div>
	
	<input type="button" value="ok">

</body>
</html>

给表格添加颜色

<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<style type="text/css">
.fen {
	background: #ff66ff;
}

.yello {
	background: #ffff66;
}

.red {
	background: #ff3333;
}

.blue {
	background: #9999ff;
}

.green {
	background: #bbff99;
}
.hui {
	background: #d6d6c2;
}
</style>

<script type="text/javascript">
  $(function(){
	 /*  $("table tr:eq(0)").addClass("fen");// eq 指定某个元素
	  $("table tr:gt(0)").addClass("hui");// gt 大于某个元素下标 */
	  
	 // 鼠标事件
	  $("table tr").hover(function(){
		  $(this).removeClass().addClass("fen");
	  },
	  function(){
		  $(this).removeClass().addClass("hui");;
	  }
	  );
	  
	  
  });

</script>

</head>
<body>
	<table border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1</td>
		</tr>
	</table>
</body>
</html>

在这里插入图片描述


jquery 自定义插件

  • 插件机制简介
    往jquery类库里面去扩展方法,这类方法就是jquery插件

json的三种格式

  1. json对象字符串体现形式
<script type="text/javascript">
	$(function() {
		// json对象字符串体现形式
		var $jsonObj1={
				sid:'1',
				sname:'小飞'
		};
        console.log($jsonObj1);
	});
</script>
  1. json数组字符串体现形式
<script type="text/javascript">
	$(function() {
		// json数组字符串体现形式
		 var $jsonArray1=[1,2,4,3];
        console.log($jsonArray1);
	});
</script>
  1. json混合模式字符串体现形式
<script type="text/javascript">
	$(function() {
		 // json混合模式字符串体现形式
        var jsons = {id:2,hobby:['a','b','c']};
        console.log(jsons);
	});
</script>

认识两个方法

$ .extend是用来扩充jquery类属性或者方法所用

$ .fn.extend() 函数为jQuery扩展一个或多个实例属性和方法(主要用于扩展方法)

<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
	$(function() {
		// json对象字符串体现形式
		var $jsonObj1={
				sid:'1',
				sname:'小飞'
		};
        console.log($jsonObj1);
        // json数组字符串体现形式
        var $jsonArray1=[1,2,4,3];
        console.log($jsonArray1);
        
        // json混合模式字符串体现形式
        var jsons = {id:2,hobby:['a','b','c']};
        console.log(jsons);
        
        // 测试值覆盖的问题,之前已经扩充的属性值会被后面的对象所覆盖,如果后面对象有新的属性,会继续扩充。
        var $jsonObj3={
				sid:'101',
				sname:'小f',
		        hobby:['a','b','c']
		};
        
        // $.extend是用来扩充jquery类属性或者方法所用
        var $jsonObj2 = {};
        //$.extend($jsonObj2,$jsonObj1);
        // 值覆盖
        $.extend($jsonObj2,$jsonObj1,$jsonObj3);
        console.log($jsonObj2);
        
        
        // 扩充方法
        $.extend({
        	  hello:function (){
        		  alert('扩充方法');
        	  }
        });
        
        $.hello();
        
        // $.fn.extend 是用来扩充jquery实例属性或者方法所用
        
        $.fn.extend({
        	  sayHello:function (){
        		  alert('你好鸭~鸭');
        	  }
        });
        
        $("#yellow").sayHello();
        
	});
</script>
</head>
<body>
      <span id="yellow">yellow</span>
</body>
</html>

jQuery插件的添加
其实就是给jQuery添加新的实例方法或类方法,然后将功能封闭在其中

jQuery插件开发实例(demo7.jsp demo8.jsp demo9.jsp)

创建两个文件 .css .js
在这里插入图片描述
jquery.table.css 文件

.fen {
	background: #ff66ff;
}

.yellow {
	background: #ffff66;
}

.out {
	background: #ff3333;
}

.blue {
	background: #9999ff;
}

.green {
	background: #bbff99;
}
.hui {
	background: #d6d6c2;
}

jquery.table.js

$(function() {
	var defaults = {
			head : 'fen',
			 out : 'yellow',
			over : 'red'
	}
		$.fn.extend({
			// 使用return 的原因是让该实例方法支持链编程,好比StringBuffer
			bgColor:function(option){
				$.extend(defaults,option)
				// 这里的this 指的是插件本身,可以看做是一个jqurey实例
				return this.each(function() {
					// this 指的是当前元素
					$("tr:eq(0)", this).addClass(defaults.head);
					$("tr:gt(0)", this).addClass(defaults.over);
					// 添加动态效果
					$("tr:gt(0)", this).hover(function() {
						$(this).removeClass().addClass(defaults.over);
					}, function() {
						$(this).removeClass().addClass(defaults.out);
					});
				});
			}
		});
});

head.jsp
把jsp重复的代码放入一个新的jsp,然后通过<%@ include file="/jsp/common/head.jsp" %>放入到jsp页面中
在这里插入图片描述

<%@ 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">
<link href="${pageContext.request.contextPath }/jquery/table/css/jquery.table.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/table/js/jquery.table.js"></script>

demo7.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ include file="/jsp/common/head.jsp" %>
<!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 type="text/javascript">
$(function(){
   $("table").bgColor();

})

</script>
</head>
<body>
	<table id="t1" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10万</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11万</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22万</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18万</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1万</td>
		</tr>
	</table>
	
	<table id="t2" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10万</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11万</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22万</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18万</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1万</td>
		</tr>
	</table>
</body>
</html>

网页显示:
在这里插入图片描述

demo8.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ include file="/jsp/common/head.jsp" %>
<!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 type="text/javascript">
	$(function(){
		$("table").bgColor({
			head : 'blue',
		     out : 'green',
		    over : 'hui'
		});
	})
</script>
</head>
<body>
	<table id="t1" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1</td>
		</tr>
	</table>
	
	<table id="t2" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1</td>
		</tr>
	</table>
</body>
</html>

网页显示:

在这里插入图片描述

demo9.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ include file="/jsp/common/head.jsp" %>
<!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">
<style type="text/css">
@import url(js/bgColor/bgColor.css);
</style>
<title>Insert title here</title>
<script type="text/javascript">
	$(function(){
		$("table").bgColor({
			head : 'out',
		     out : 'yellow',
		    over : 'hui'
		});
	})
</script>
</head>
<body>
	<table id="t1" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1</td>
		</tr>
	</table>

	<table id="t2" border="1" width="100%">
		<tr>
			<td>书名</td>
			<td>作者</td>
			<td>点击量</td>
		</tr>
		<tr>
			<td>圣墟</td>
			<td>辰东</td>
			<td>10</td>
		</tr>
		<tr>
			<td>飞剑问道</td>
			<td>我吃西红柿</td>
			<td>11</td>
		</tr>
		<tr>
			<td>杀神</td>
			<td>逆苍天</td>
			<td>22</td>
		</tr>
		<tr>
			<td>龙王传说</td>
			<td>唐家三少</td>
			<td>18</td>
		</tr>
		<tr>
			<td>斗破苍穹</td>
			<td>天蚕拖豆</td>
			<td>1</td>
		</tr>
	</table>
</body>
</html>

网页显示:
在这里插入图片描述


ajax

jackson
Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json对象
和xml文档,同样也可以将json、xml转换成Java对象

核心代码:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(obj);
方法可以把java对象转化成json字符串

int count = md.getColumnCount();
map.put(md.getColumnName(i), rs.getObject(i));
getColumnName(int index),这个方法获取的是该字段在表内的名称。

jackson需要导入夹包:
在这里插入图片描述

后台json 的三种格式的体现形式
package com.hyf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyf.entity.Student;

/**
 * 后台json 的三种格式的体现形式
 * @author 17628
 *
 */
public class Demo1 {
   public static void main(String[] args) throws JsonProcessingException {
	   // json 对象
	   Student stu1 = new Student("s001", "张三");
	   ObjectMapper om = new ObjectMapper();
	   System.out.println("对象:"+om.writeValueAsString(stu1));
	   
	   // json 数组
	   Student stu2 = new Student("s002", "李四");
	   List<Student> list1 = new ArrayList<Student>();
	   list1.add(stu1);
	   list1.add(stu2);
	    System.out.println("数组:"+om.writeValueAsString(list1));
	   
	   // json 混合格式
	   Map<String, Object> map = new HashMap<String, Object>();
	   map.put("total", 2);
	   map.put("stus", list1);
	   System.out.println("混合格式:"+om.writeValueAsString(map));
  }
}

输出结果:
在这里插入图片描述

javabean 与 map集合转换成json字符串格式是一样的
package com.hyf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * javabean 与 map集合转换成json字符串格式是一样的
 * @author 17628
 *
 */
public class Demo2 {
   public static void main(String[] args) throws JsonProcessingException {
	Map<String, Object> stu1 = new HashMap<String, Object>();
	stu1.put("sid", "s001");
	stu1.put("sname", "张三");
	ObjectMapper om = new ObjectMapper();
	String wvas = om.writeValueAsString(stu1);
	System.out.println(wvas);
//	{"sname":"张三","sid":"s001"}
//	混合格式:{"total":2,"stus":[{"sid":"s001","sname":"张三","teas":[]},
//	{"sid":"s002","sname":"李四","teas":[]}]}
	
	Map<String, Object> stu2 = new HashMap<String, Object>();
	stu2.put("sid", "s002");
	stu2.put("sname", "李四");
	List<Map<String,Object>> list1 = new ArrayList<>();
	list1.add(stu1);
	list1.add(stu2);
	System.out.println(om.writeValueAsString(list1));
	
	//{"sname":"张三","sid":"s001"}
	//[{"sname":"张三","sid":"s001"},{"sname":"李四","sid":"s002"}]
	
}
}

3. java->json死循环

下面代码演示学生与老师多对多关系

Studnet 类

package com.hyf.entity;

import java.util.HashSet;
import java.util.Set;

public class Student {
	private String sid;
	private String sname;
	private Set<Teacher> teas = new HashSet<>(); 
	
	public Set<Teacher> getTeas() {
		return teas;
	}
	public void setTeas(Set<Teacher> teas) {
		this.teas = teas;
	}
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", teas=" + teas + "]";
	}
	public Student(String sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
	}
	public Student() {
		super();
	}
	public Student(String sid, String sname, Set<Teacher> teas) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.teas = teas;
	}
    
}

Teacher 类

package com.hyf.entity;

import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreType;


public class Teacher {
	private String tid;
	private String sname;
//	@JsonIgnore
	private Set<Student> stus = new HashSet<>();

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public Set<Student> getStus() {
		return stus;
	}

	public void setStus(Set<Student> stus) {
		this.stus = stus;
	}

	@Override
	public String toString() {
		return "Teacher [tid=" + tid + ", sname=" + sname + ", stus=" + stus + "]";
	}

	public Teacher(String tid, String sname, Set<Student> stus) {
		super();
		this.tid = tid;
		this.sname = sname;
		this.stus = stus;
	}

	public Teacher() {
		super();
	}

	
}

/**
 - json 死循环问题 java.lang.StackOverflowError
 - 1由双向绑定改成单项绑定,也就是说彼此之间的关系交于一方维护。
 - 2、@JsonIgnore:将彼此循环调用的属性忽略,不参与对象转成json格式
 - @author 17628
 -  */
public class Demo3 {
	public static void main(String[] args) throws JsonProcessingException {
        Student stu1 = new Student("s001", "光头强");
        Student stu2 = new Student("s002", "熊大");
        Student stu3 = new Student("s003", "熊二");
        Teacher tea1 = new Teacher("t001", "小刀", null);
        Teacher tea2 = new Teacher("t002", "刘哥", null);
        
        Set<Teacher> teas = new HashSet<>();
        teas.add(tea1);
        teas.add(tea2);
        stu1.setTeas(teas);
        
        Set<Student> stus = new HashSet<>();
        stus.add(stu1);
        stus.add(stu2);
        stus.add(stu3);
        tea1.setStus(stus);
        ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(stu1));
	}
}

在这里插入图片描述
解决办法
第一种

  • 由双向绑定改成单项绑定,也就是说彼此之间的关系交于一方维护。

第2种解决方法(Studnt 类也可行)
在这里插入图片描述


$.ajax实现省市联动

ResponseUtil:在

package com.hyf.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
}

JsonUtils:专门用来处理json数据的共用包

package com.hyf.util;

import java.util.Arrays;
import java.util.Map;

/**
 * 专门用来处理json数据的共用包
 * @author 17628
 *
 */
public class JsonUtils {
	/**
	 * 从paraMap拿到 咱们所需要用到的查询维度,用于sql语句拼接
	 * @param paraMap  获取从jsp页面传递到后台的参数集合
	 * @return
	 */
	public  static  String getParamVal(Map<String,String[]> paraMap,String key) {
		if(paraMap !=null && paraMap.size()>0) {
			String[] vals = paraMap.get(key);
			if(vals != null && vals.length > 0) {
				String val = Arrays.toString(vals);
				return val.substring(1,val.length()-1);
			}
			return "";
		}
		return "";
	}
}

BaseDao < T >:通用查询工具包

package com.hyf.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 通用的查询方法 23种设计模式之策略模式 
 * 作用:在方法或类中已经完成了对应的功能,然后在调用方去根据自己的需求去处理结果。 使得代码更加灵活。
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
	// $.ajax
	protected interface Callback<T> {
		public List<T> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException;
	}

	public List<T> executeQuery(String sql, PageBean pageBean, Callback<T> callback)
			throws SQLException, InstantiationException, IllegalAccessException {
		if (pageBean != null && pageBean.isPagination()) {
			Connection con = DBAccess.getConnection();
			String countSql = getCountSql(sql);
			PreparedStatement countPst = con.prepareStatement(countSql);
			ResultSet countRs = countPst.executeQuery();
			if (countRs.next()) {
				pageBean.setTotal(countRs.getObject(1).toString());
			}
			DBAccess.close(null, countPst, countRs);

			String pageSql = getPageSql(sql, pageBean);
			PreparedStatement pagePst = con.prepareStatement(pageSql);
			ResultSet pageRs = pagePst.executeQuery();
			return callback.foreach(pageRs);
		} else {
			Connection con = DBAccess.getConnection();
			PreparedStatement pst = con.prepareStatement(sql);
			ResultSet rs = pst.executeQuery();
			return callback.foreach(rs);
		}

	}

	/**
	 * 将原生态的sql语句转换成查对应的当页记录数sql语句
	 * 
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPageSql(String sql, PageBean pageBean) {
		return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
	}

	/**
	 * 将原生态的sql语句转换成查总记录输的sql语句
	 * 
	 * @param sql
	 * @return
	 */
	private String getCountSql(String sql) {
		return "select count(1) from (" + sql + " ) t";
	}
}

JsonBaseDao :继承BaseDao < T >

package com.hyf.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonBaseDao extends BaseDao<Map<String,Object>> {
	public List<Map<String,Object>> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		return super.executeQuery(sql, pageBean, new Callback<Map<String,Object>>() {

			public List<Map<String,Object>> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException {
				/*
				 * 1、创建一个实体类的实例
				 * 2、给创建的实例属性赋值
				 * 3、将添加完类容的实体类添加到list集合中/
				List<Map<String,Object>> list = new ArrayList<>();
//				获取源数据
				ResultSetMetaData md = rs.getMetaData();
				int count = md.getColumnCount();
				Map<String, Object> map = null;
				while(rs.next()) {
					map = new HashMap<>();
					for(int i=1;i<=count;i++) {
						map.put(md.getColumnName(i), rs.getObject(i));
					}
					list.add(map);
				}
				return list;
			} 
		});
	}
}

RegionDao

package com.hyf.dao;

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

import com.hyf.util.JsonBaseDao;
import com.hyf.util.JsonUtils;
import com.hyf.util.PageBean;
import com.hyf.util.StringUtils;

public class RegionDao extends JsonBaseDao {

	 public List<Map<String,Object>> list(Map<String,String[]> paraMap,PageBean pagebean) throws InstantiationException, IllegalAccessException, SQLException{
		 String id = JsonUtils.getParamVal(paraMap, "ID");
		 String sql = "select * from ch_region where true";
		 //StringUtils 自定义的工具类 判断字符是否为null 和 ""
		 if(StringUtils.isBlank(id)) {
			 sql += " and parent_id=7459";
		 }else {
			 sql += " and parent_id="+id;
		 }
		 return super.executeQuery(sql, pagebean);
	 }
	 
}

配置xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>web_jquery</display-name>
  <!--解决乱码  -->
  <filter>
        <filter-name>encodingFiter</filter-name>
        <filter-class>com.hyf.util.EncodingFiter</filter-class>
  </filter>
  <filter-mapping>
        <filter-name>encodingFiter</filter-name>
        <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
  <servlet>
     <servlet-name>regionServlet</servlet-name>
     <servlet-class>com.hyf.web.RegionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>regionServlet</servlet-name>
     <url-pattern>/regionServlet</url-pattern>
  </servlet-mapping>

</web-app>

RegionServlet

package com.hyf.web;

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

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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyf.dao.RegionDao;
import com.hyf.util.ResponseUtil;

public class RegionServlet extends HttpServlet {

	private static final long serialVersionUID = 6531004209491725231L;
	private RegionDao regionDao = new RegionDao();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			List<Map<String, Object>> list = regionDao.list(req.getParameterMap(), null);
			ObjectMapper om = new ObjectMapper();
			try {
				ResponseUtil.write(resp, om.writeValueAsString(list));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
	}

}

js

$(function() {
	var ctx = $("#ctx").val();
     $.ajax({
    	 url : ctx+"/regionServlet",
    	 success:function(data){
            for(index in data){
            	console.log(data[index]);
            	$("#province").append("<option value='"+data[index].ID+"'>"+data[index].REGION_NAME+"</option>");
            }
    	 },
    	 dataType:"json"
     });
     
     $("#province").change(function(){
    	 $("option:gt(0)","#city").remove();
    	 $.ajax({
    		 url : ctx+"/regionServlet?ID="+this.value,
    		 success:function(data){
    			 for(index in data){
    				 $("#city").append("<option value='"+data[index].ID+"'>"+data[index].REGION_NAME+"</option>");
    			 }
    		 },
    		 dataType:"json"
    	 });
     });
     
     
});

jsp 文件

<%@ 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">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/demo10.js"></script>
<title>Insert title here</title>
</head>
<body>
<div>
    <input type="hidden" id="ctx" value="${pageContext.request.contextPath}"/>
	<h1>$.ajax实现省市联动</h1>
	<div>
		收货地址&nbsp;&nbsp;
		<select id="province">
			<option selected="selected">---请选择省份---</option>
		</select>&nbsp;&nbsp;
		<select id="city">
			<option selected="selected">---请选择城市---</option>
		</select>&nbsp;&nbsp;
		<select id=" county">
			<option selected="selected">---请选择县区---</option>
		</select>
	</div>
</div>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值