jquery

一、入门
什么是jQuery
它是一个轻量级的javascript类库

注1:就一个类“jQuery”,简写“$”

jQuery优点
2.1 总是面向集合
2.2 多行操作集于一行

hello jQuery
3.1 导入js库

3.1.1 在jsp页面导入jquery

<scripttype=“text/javascript"src=”${pageContext.request.contextPath}/js/jquery.min.js">


 	$(function() {
		alert("hello jquery");
	}) 
	
//	 $(document).readyfunction() {
//		alert("hello jquery2");
//	}
	
//	window.onload = function(){
//		alert("hello jquery3");
//	}
	/* 

结果:
在这里插入图片描述
$(fn).document.ready(fn)与window.onload的区别:

1.$(function), $(document).ready(function)是等价的,哪个代码在前面哪个先执行
jsp的dom树结构加载完毕即可调用方法

window.onload = function()最后执行
jsp的dom树加载完,css,jsp等静态资源加载完毕执行
jQuery三种工厂方法 (demo2.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>
<title>Insert title here</title>
<script type="text/javascript">
/*$(fn).document.ready(fn)与window.onload的区别?
	项目维护时候要用到
*/

 	$(function() {
		alert("hello jquery1");
	}) 
	
	 $(document).readyfunction() {
		alert("hello jquery2");
	}
	
	window.onload = function(){
		alert("hello jquery3");
	}
	/* 
	结论:$(function),  $(document).ready(function)是等价的,哪个代码在前面哪个先执行
		jsp的dom树结构加载完毕即可调用方法
	
		window.onload = function()最后执行
		jsp的dom树加载完,css,jsp等静态资源加载完毕执行
		*/

</script>
</head>
<body>
	
</body>
</html>

jQuery(html) (demo3.jsp) html:基于html的一个字符串
jQuery(element) (demo3.jsp) element:js对象,表示一个html元素对 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() {
		$(":input[name='name1']").click(function() {
			//在id=selId1的select的jQuery实例上追加"<option value='1'>湖南省</option>"的HTML jQuery实例
			$("#selId1").append("<option value='1'>湖南省</option>");
		});
		
		$(":input[name='name2']").click(function() {
			//将<option value='1'>长沙市</option>的HTML jQuery实例追加到id=selId2的select标签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");
			//获取jQuery对象
			alert(h2Node.value);
			//js对象转jQuery对象      (h2Node.val())是js对象
			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>
<%@ 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() {
		$(":input").click(function() {
			//this指的是事件源
			alert(this.value);
			$("a").each(function(index,itme) {
				//这里的this指的是当前元素
				alert(index+","+$(this).html()+","+$(itme).html());
			})
		});
	})
</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>
	
	<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>
<style type="text/css">
.fen {
	background: #ff66ff;
}

.yello {
	background: #ffff66;
}

.red {
	background: #ff3333;
}
</style>
<script type="text/javascript">
$(function(){
	$("table tr:eq(0)").addClass("yello");
	$("table tr:gt(0)").addClass("red");
	xa

	$("table tr:gt(0)").hover(function(){
		$(this).removeClass().addClass("fen");
	},function(){
		$(this).removeClass().addClass("red");
	});
})
</script>
<title>Insert title here</title> 
</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>

注1:$就是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:'s001',
				sname:'zhangsan'
		};
		console.log(jsonObj1);
		//json数组的字符串体现形式
		var jsonArray1=[1,3,4,5];
		console.log(jsonArray1);
		//json混合模式的字符串体现形式
		var jsons = {id:3,hobby:['a','b','c']};
		console.log(jsons);
		
		var jsonObj3 = {
				sid:'s002',
				sname:'lisi',
				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();
		alert("yellow");
		
	})
</script>
</head>
<body>
<span id="yellow">yellow</span>
</body>
</html>

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE>
<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>

css样式:

@charset "UTF-8";
.fen {
	background: #ff66ff;
}

.yellow  {
	background: #ffff66;
}

.red {
	background: #ff3333;
}

.blue {
	background: #9999ff;
}

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

自定义js:

    $(function(){
	var defaults = {
			head : 'yello',
			out  : 'red',
			over : 'blue'
	}
	$.fn.extend({
		//使用return的原因是让该实例方法支持链编程,好比stringbuffer
		bgColor:function(option){
			$.extend(defaults,option);
			//这里的this指的是插件本身,可以看成一个jquery实例。
			return this.each(function(){
				//this指的是当前元素
				$("tr:eq(0)",this).addClass(defaults.head);
				$("tr:gt(0)",this).addClass(defaults.out);
				
				//添加动态效果
				$("tr:gt(0)",this).hover(function(){
					$(this).removeClass().addClass(defaults.over);
				},function(){
					$(this).removeClass().addClass(defaults.out);
				});
			});
		}
	});
})
<%@ 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">
.over{
	background:  #ff66ff;
}
.out{
	background: #ffff66;
}
.head{
	background: #ff3333;
}
</style>

<script type="text/javascript">
	$(function(){
		$("table").each(function(){
			//给默认值
			$("tr:eq(0)",this).addClass('head');
			$("tr:gt(0)",this).addClass('out');
			
			//添加动态效果
			$("tr:gt(0)",this).hover(function(){
				$(this).removeClass().addClass('over');
			},function(){
				$(this).removeClass().addClass('out');
			});
		});
		
	})
</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>
<%@ 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">
<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>
<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>
<%@ 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 : 'yellow',
			out  : 'red',
			over : 'blue'
	});
		
	})
</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>

后台json的三种格式的体现形式

package com.wangjing;

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.wangjing.entity.Student;

/**
 * 后台json的三种格式的体现形式
 * @author wj
 *
 */
public class Demo1 {
	public static void main(String[] args) throws Exception {
		//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.wangjing;

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

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * javaBean与Map集合转化成json字符格式是一样的
 * @author wj
 *
 */
public class Demo2 {
	public static void main(String[] args) throws IOException {
		Map<String, Object> stu1 = new HashMap<String, Object>();
		stu1.put("sid", "001");
		stu1.put("sname", "张三");
		ObjectMapper om=new ObjectMapper();
		System.out.println(om.writeValueAsString(stu1));
		
		Map<String, Object> stu2=new HashMap<>();
		stu2.put("sid", "s002");
		stu2.put("sname", "李四");
		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		list1.add(stu1);
		list1.add(stu2);
		System.out.println(om.writeValueAsString(list1));
		
	}
}
Student实体类
```java
package com.wangjing.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 Student(String sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
	}
	public Student() {
		super();
	}
	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;
	}
	public Set<Teacher> getTeas() {
		return teas;
	}
	public void setTeas(Set<Teacher> teas) {
		this.teas = teas;
	}
	
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", teas=" + teas + "]";
	}
}

Teacher实体类:

package com.wangjing.entity;

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

import com.fasterxml.jackson.annotation.JsonIgnore;

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死循环的问题

  • 1、由双向绑定改成单项绑定,也就是是将彼此之间的关系交于一方维护。
  • 2、@JsonIgnore:将彼此循环调用的属性忽略,不参与对象转成json格式
package com.wangjing;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangjing.entity.Student;
import com.wangjing.entity.Teacher;

/**
 * json死循环的问题
 * 1、由双向绑定改成单项绑定,也就是是将彼此之间的关系交于一方维护。
 * 2、@JsonIgnore:将彼此循环调用的属性忽略,不参与对象转成json格式
 * @author wj
 *
 */
public class Demo3 {
	public static void main(String[] args) throws IOException {
		Student stu1 = new Student("s001", "老胡");
		Student stu2 = new Student("s002", "老邱");
		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);
		tea1.setStus(stus);
		ObjectMapper om = new ObjectMapper();
		System.out.println(om.writeValueAsString(stu1));
	}
}

省市二级联动

工具类
DBAccess 连接数据库

package com.wangjing.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.jdbc.Driver".equals(driver);
	}

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

BaseDao 通用的查询方法

package com.wangjing.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
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";
	}
}

StringUtils 如果字符串等于null或去空格后等于"",则返回true,否则返回false

package com.wangjing.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

ResponseUtil

package com.wangjing.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();
	}
}

PageBean 分页工具类

package com.wangjing.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	 private int page = 1;// 页码 	
	 private int rows = 10;// 页大小 	
	 private int total = 0;// 总记录数  	
	 //保留上一次 的请求地址
	 private String url="";
	 //保留上一次请求所携带的参数
	 private  Map<String, String[]> paMap=new HashMap<>();
	 /** * pageBean初始化的方法
	  * @param req 
	  */   
	   public void setRequest(HttpServletRequest req) {    	
	   //改变它第几页的数据    	
	   this.setPage(req.getParameter("page"));    	
	   //改变它每页展示的数据//    	
	   System.out.println(req.getParameter("rows"));    	
	   if(req.getParameter("rows")!=null) {    	
	   this.setRows(Integer.parseInt(req.getParameter("rows")));    	
	   }else {    		
	   this.setRows(10);    	
	   }    	
	   //控制页面是否分页    	
	   this.setPagination(req.getParameter("pagination"));    	    	    	
	   this.setUrl(req.getRequestURL().toString());//上一次的地址    	
	   this.setPaMap(req.getParameterMap());//上一次查询的参数   
	    } 	
	    private void setPagination(String parameter) {		
	    // 当你填false就不分页		
	    if("false".equals(pagination)) {			
	    this.setPagination(false);		
	    }	
	    }    
	    public void setPage(String page) {//    	如果不为空的时候    	
	    if(StringUtils.isNotBlank(page)) {    		
	    this.setPage(Integer.valueOf(page));    	
	    }   
	     }	
	     public String getUrl() {	
	     return url;
	     } 
	     public void setUrl(String url) {	
	     this.url = url
	     ;}   	
	     public Map<String, String[]> getPaMap() {	
	     return paMap;
	     } 
	     public void setPaMap(Map<String, String[]> paMap) {	
	     this.paMap = paMap;
	     }   	
	     private boolean pagination = true;// 是否分页 	
	     public PageBean() {		
	     super();
	     	} 	
	     	public int getPage() {		
	     	return page;	
	     	} 	
	     	public void setPage(int page) {		
	     	this.page = page;	
	     	} 	
	     	public int getRows() {		
	     	return rows;	
	     	} 	
	     	public void setRows(int rows) {		
	     	this.rows = rows;	
	     	} 	
	     	public int getTotal() {		
	     	return total;
	     		} 	
	     		public void setTotal(int total) {		
	     		this.total = total;	
	     		} 	
	     		public void setTotal(String total) {		
	     		this.total = Integer.parseInt(total);	
	     		} 	
	     		public boolean isPagination() {		
	     		return pagination;
	     			} 	
	     			public void setPagination(boolean pagination) {		
	     			this.pagination = pagination;	
	     			} 	
	     			/**	 
	     			*获得起始记录的下标	 
	     			* 	 
	     			* @return	 
	     			* */	
	     			public int getStartIndex() {		
	     			return (this.page - 1) * this.rows;	
	     			} 	
	     			@Override	
	     			public String toString() {		
	     			return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";	
	     			}
	     			/** * 最大页码 
	     			* @return 
	     			* */	
	     			public int getMaxPage() {	
	     			return this.total%this.rows==0? this.total/this.rows:this.total/this.rows+1;			}	
	     			/**	
	     			 * 获取下一页	
	     			 * @return	 
	     			 * */  
	     			 public int getNextPage() {	
	     			 return this.page<this.getMaxPage()?this.page+1:this.page;	    
	     			 }
	     			   
	 public int getPreviousPage() {	
	     			   return this.page>1?this.page-1:this.page;	    
	     			   }

	
}

JsonUtils 专门用来处理json数据的工具包

package com.wangjing.util;

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

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

JsonBaseDao
1、创建一个实体类的实例
2、给创建的实例属性赋值
3、将添加完类容的实体类添加到list集合中

package com.wangjing.util;

import java.lang.reflect.Field;
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.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				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.getColumnClassName(i), rs.getObject(i));
					}
					list.add(map);
				}
				
				return list;
			}
		});
	}
}

EncodingFiter 中文乱码处理

package com.wangjing.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

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 EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

配置文件

<?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>jquery</display-name>
 	<servlet>
 		<servlet-name>regionServlet</servlet-name>
 		<servlet-class>com.wangjing.web.RegionServlet</servlet-class>
 	</servlet>
 	<servlet-mapping>
 		<servlet-name>regionServlet</servlet-name>
 		<url-pattern>/regionServlet</url-pattern>
 	</servlet-mapping>
</web-app>

RegionDao

package com.wangjing.dao;

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

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

public class RegionDao extends JsonBaseDao{
	public List<Map<String, Object>> list(Map<String, String[]> paramMap,PageBean pageBean) throws Exception, Exception, Exception{
		String id = JsonUtils.getParamVal(paramMap, "ID");
		String sql = "select * from ch_region where true ";
		if(StringUtils.isBlank(id)) {
			sql +=" and parent_id=7459";
		}else {
			sql +=" and parent_id="+id;
		}
		return super.executeQuery(sql, pageBean);
	}
	public static void main(String[] args) throws Exception {
		Map<String, String[]> paramMap = new HashMap<String, String[]>();
		paramMap.put("ID", new String [] {"9504"});
		RegionDao regionDao = new RegionDao();
		List<Map<String, Object>> list = regionDao.list(paramMap,null);
		System.out.println(list);
	}
}

$(function() {
	var ctx = $("#ctx").val();
	$.ajax({
		url:ctx+"regionServlet",
		success:function(data){
			for(index in data){
				$("#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>");
				}
			},
		});
	});
})

显示页面

<%@ 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>
<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>

显示结果:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值