1、同步和异步
同步:同步请求,客户端发出请求,等待服务器端返回结果,接着进行下一次的请求。
异步:异步请求,客户端发出请求,无需等待服务器端返回结果,接着进行下一次的请求。
2、Ajax简介
Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
原理:
1、客户端发送异步请求
XMLHttpRequest 对象
2、服务器端接收请求,处理数据,通常返回json格式的数据,字符串(文本)
3、客户端获取服务器返回的数据在页面上显示
使用js ,jquery ,dom ,css
3、JQuery中的AJAX
$.get 发出的是get请求
$.get(url,[data],[callback],[type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。 发送给服务器的数据 键值对结构
callback:载入成功时回调函数。 function(d){ d代表服务器返回的结果}
type:返回内容格式,xml, html, script, json, text, _default。
示例1:
添加部门时检测部门名称是否已经存在
1、在web目录下创建static文件夹,在static下创建js,css,image三个文件夹,将jQuery的文件拷贝到js文件夹中
2、addDept.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="/static/js/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$("#dname").on("blur",function(){
$.get(
"/deptServlet/checkDeptName",
{dname:$("#dname").val()},
function(result){
if(result==1){
$("#deptmsg").html("部门已存在");
}else{
$("#deptmsg").html("");
}
}
);
})
})
</script>
</head>
<body>
<form action="/userServlet/add" method="post">
部门名称:<input name="dname" id="dname"><span id="deptmsg"></span><br>
创建时间:<input type="date" name="createDate"><br>
<input type="submit" value="添加" id="btn">
</form>
</body>
</html>
DeptDao、DeptDaoImpl省略
3、DeptServlet
package com.aaa.servlet;
@WebServlet(value = "/deptServlet/*")
public class DeptServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String uri=request.getRequestURI();
String method=uri.substring(uri.lastIndexOf("/")+1);
String target="";
switch(method){
case "checkDeptName":target=checkDeptName(request,response);break;
...
}
if(target!=null){
request.getRequestDispatcher(target).forward(request,response);
}
}
private String checkDeptName(HttpServletRequest request, HttpServletResponse response) throws IOException {
String dname=request.getParameter("dname");
DeptDao dd=new DeptDaoImpl();
int i=dd.checkDeptName(dname);
PrintWriter out=response.getWriter();
out.println(i);
out.close();
return null;
}
...
}
4、在部门名称文本框输入部门名称,然后切换焦点,会出现提示
$.post
$(url,[data],[callback],[type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
示例2
添加部门,添加后获得所有部门信息在添加form下的表格显示
1、addDept.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="/static/js/jquery-1.8.3.min.js"></script>
<script src="/static/js/myjs.js"></script><!--引入jQuery的通用操作函数-->
<script>
$(function(){
$("#dname").on("blur",function(){
$.get(...);
})
})
$(function(){
$("#btn").click(function(){
$.post(
"/deptServlet/add",
$("#form").serialize(),//将表单数据序列化
function(depts){
addTab("tb",depts,["deptno","dname","createTime"]);
//将json数据添加到表格
},
"json"
);
});
})
</script>
</head>
<body>
<form id="form" method="post">
部门名称:<input name="dname" id="dname"><span id="deptmsg"></span><br>
创建时间:<input type="date" name="createTime"><br>
<input type="button" value="添加" id="btn">
</form>
<hr>
<table border="1" width="400px">
<tr>
<th>部门编号</th>
<th>部门名称</th>
<th>创建日期</th>
</tr>
<tbody id="tb"></tbody>
</table>
</body>
</html>
2、DeptServlet代码
需要添加阿里的fastjson.jar包
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* JSON转换
*/
public class App
{
public static void main( String[] args )
{
//1。通过对象生成JSON串,对象里包含对象数组转成JSON串。
Person person=new Person();
person.setUsername("xiejava");
person.setSex("man");
person.setAge(38);
person.setEmail("xiejava@ishareread.com");
Card card1=new Card();
card1.setCardName("bankCard1");
card1.setCardCode("888888888");
card1.setCardValue(99999999);
Card card2=new Card();
card2.setCardName("bankCard2");
card2.setCardCode("999999999");
card2.setCardValue(222222222);
//对象数组
Listcards=new ArrayList();
cards.add(card1);
cards.add(card2);
person.setCardList(cards);
String json = JSON.toJSON(person).toString();
System.out.println(json);
//2.通过JSON对象生成JSON串
JSONObject jObject=new JSONObject();
jObject.put("username", "xiejava");
jObject.put("sex", "man");
jObject.put("age", 38);
jObject.put("email", "xiejava@ishareread.com");
//通过JSONArray包装对象数组
JSONArray jArray=new JSONArray();
jArray.addAll(cards);
jObject.put("cardList", jArray);
String json2=jObject.toJSONString();
System.out.println(json2);
//3.通过JSON对象生成JSON串
JSONObject jObject2=new JSONObject();
jObject2.put("username", "xiejava");
jObject2.put("sex", "man");
jObject2.put("age", 38);
jObject2.put("email", "xiejava@ishareread.com");
//构造JSON字符串
String cardjsonStr1="{\"cardName\":\"bankCard1\",\"cardCode\":\"888888888\",\"cardValue\":99999999}";
String cardjsonStr2="{\"cardName\":\"bankCard2\",\"cardCode\":\"999999999\",\"cardValue\":222222222}";
JSON.parseObject(cardjsonStr1);
JSONArray jArray2=new JSONArray();
//将JSON字符串转成JSON对象,加入到JSONArray,[注意一定要用JSON.parseObject()方法转换成JSON对象,否则还是字符串,转成JSON串的时候会带双引号。]
jArray2.add(JSON.parseObject(cardjsonStr1));
jArray2.add(JSON.parseObject(cardjsonStr2));
jObject2.put("cardList", jArray2);
String json3=jObject2.toJSONString();
System.out.println(json3);
}
}
DeptServlet
package com.aaa.servlet;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.beanutils.BeanUtils;
...
@WebServlet(value = "/deptServlet/*")
public class DeptServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri=request.getRequestURI();
String method=uri.substring(uri.lastIndexOf("/")+1);
String target=null;
switch(method){
case "checkDeptName":target=checkDeptName(request,response);break;
case "add":target=add(request,response);break;
case "showAll":target=showAll(request,response);break;
}
if(target!=null){
request.getRequestDispatcher(target).forward(request,response);
}
}
private String checkDeptName(HttpServletRequest request, HttpServletResponse response) throws IOException {
。。。
}
private String add(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Map<String, String[]> map = request.getParameterMap();
Dept dept=new Dept();
try {
BeanUtils.populate(dept,map);//填充dept对象属性值
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
DeptDao dao=new DeptDaoImpl();
dao.addDept(dept);//添加到数据库
return showAll(request,response);//添加过后调用查询所有部门方法
}
private String showAll(HttpServletRequest request, HttpServletResponse response){
DeptDao dao=new DeptDaoImpl();
List<Dept> list=dao.findAllDept();
response.setContentType("text/html;charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
String s = JSONArray.toJSONString(list);//将Dept对象列表转化为JSON字符串
System.out.println(s);
out.println(s);
out.close();
return null;
}
}
录入后效果出错
日期显示的是长整型的数字
需要在实体类的属性上添加注解:@JSONField(format=“yyyy-MM-dd HH:mm:ss”),这也是阿里fastjson.jar包中的注解。
import com.alibaba.fastjson.annotation.JSONField;
public class Dept {
private int deptno;
private String dname;
@JSONField(format="yyyy-MM-dd")
private java.sql.Date createTime;
。。。
}
再次测试正常
$.ajax
$.ajax({
type: "POST",
url: "some.jsp",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
},
dataType:"json"
});
3 异步查询分页
1、分页原理
mysql分页
select * from t_user limit startIndex,pageSize;
startIndex:(当前页数-1)*pageSize
pageSize:每页条数
发送请求时提供的参数:
1、当前页:pageNo
2、每页条数:pageSize =6
需要后台提供的数据:
1、查询到的集合
2、总页数、当前页码(后面再讲)
示例代码:
第一步:无条件分页
Page代码:
public class PageBean {
private Integer pageNo=1;
private Integer pageSize=6;
private String factor;
...
}
deptPage.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>分页</title>
<script src="static/js/jquery-3.5.1.min.js"></script>
<script src="static/js/myjs.js"></script>
</head>
<body>
<form id="form" method="post">
部门名称:<input name="dname" id="dname">
<input type="button" value="查询" id="btn">
</form>
<hr>
<table border="1" width="600px">
<tr>
<th>部门编号</th>
<th>部门名称</th>
<th>创建日期</th>
</tr>
<tbody id="tb"></tbody>
</table>
<script>
let pageBean=new Object();//创建装载分页参数的PageBean对象
pageBean.pageSize=6;//设置每页显示的行数
function search(num) {//num是要查询第几页的页数
if (num > 0) {
pageBean.pageNo = num;//如果页数正常则赋值
}else{
pageBean.pageNo=1;//否则就是第一页
}
$.ajax({
url:"/deptController/findByPage",
type:"post",
data:pageBean,//将pageBean作为参数直接传递
success:function(list){
$("#tb").empty();//清空tbody中的内容
addTab("tb",list,["deptno","dname","createTime"]);//将数据添加到指定表格中
$("#num").html(pageBean.pageNo);//修改当前页数的显示
},
dataType:"json"
})
}
$(function(){//在页面加载和点按钮时调用search()函数,查询第一页数据
search(1);
$("#btn").click(function(){
search(1);
})
})
</script>
当前是第<span id="num"></span>页 总共有<span id="totalPage"></span>页
<a href="javascript:search(pageBean.pageNo-1)">上一页</a>
<a href="javascript:search(pageBean.pageNo+1)">下一页</a>
<hr>
</body>
</html>
DeptDaoImpl:
public class DeptDaoImpl implements DeptDao {
@Override
public List<Dept> findByPage(PageBean page) {
String sql="select deptno,dname,createTime from dept limit ?,?";
try {
List<Map> dlist=BaseDB.queryMap(sql,
(page.getPageNo()-1)*page.getPageSize(),page.getPageSize());
return TransBean.populate(Dept.class,dlist);//将dlist转换为List<Dept>
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
DeptServlet
@WebServlet(value = "/deptController/*")
public class DeptServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String uri=request.getRequestURI();
String method=uri.substring(uri.lastIndexOf("/")+1);
String target=null;
switch(method){
case "findByPage":target=findByPage(request,response);break;
}
if(target!=null){
request.getRequestDispatcher(target).forward(request,response);
}
}
private String findByPage(HttpServletRequest request, HttpServletResponse response) {
PageBean pageBean=new PageBean();
try {
BeanUtils.populate(pageBean,request.getParameterMap());
List<Dept> dlist=deptDao.findByPage(pageBean);
String jsonStr=JSON.toJSONString(dlist);
output(response,jsonStr );
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
这里使用的TransBean(2020-08-21日修改)
package com.aaa.util;
import com.aaa.dao.BaseDB;
import com.aaa.entity.Dept;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.*;
public class TransBean {
/**
* 根据request传来的参数Map,和指定的实体Bean的属性进行比较,将二者名称相同的参数转换成属性类型的值,
* 并调用相应的set方法给Bean的属性赋值,
*
* @param map=request.getParameterMap();
* @param obj 要填充的对象
*
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void populate(Object obj,Map<String,String[]> map){
Set<String> keySet=map.keySet();
Class objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
try {
for(Field field:fields){
String propName=field.getName();
if(field.getType().isArray()
||field.getType().getName().equals("java.util.List")){
if (map.get(propName) != null ||map.get(propName + "[]") != null) {
//如果数组中有多个元素
//如果参数是数组,则其名称可能为"xxx[]"(ajax传来的json对象参数),所以要将后面的“[]”去掉再和属性名进行比较
field.setAccessible(true);
field.set(obj, convertArray(
map.get(propName) == null ?
map.get(propName + "[]") : map.get(propName),
field.getType().getComponentType()));
//将字符串数组转换成该属性的数组类型并赋值getComponentType():获得数组中元素的类型
}
}else {
if (map.get(propName) != null && map.get(propName).length == 1 && map.get(propName)[0] != null) {//如果值数组只有一个元素并且不为空
field.setAccessible(true);//设置属性可访问
field.set(obj, convert(map.get(propName)[0], field.getType()));//将字符串转换成该属性的类型并赋值
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static List populate(Class objClass,List<Map> listMapData){
if(listMapData==null||listMapData.size()==0)return null;
List list=new ArrayList();
Field[] fields = objClass.getDeclaredFields();//获得该类型所有声明的属性
try {
for(Map map:listMapData) {
Object obj=objClass.newInstance();//创建实体类对象
for (Field field : fields) {//遍历所有属性
String propName = field.getName();//获得当前属性的名称
if (map.containsKey(propName)){//如果map中包含该属性
field.setAccessible(true);//设置属性可访问
field.set(obj,
convert(map.get(propName)==null?
"":map.get(propName).toString(),
field.getType()));
//给该属性设置值(这里将所有类型的值都转换成string,然后再转换成该属性对应的类型)
}
}
list.add(obj);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
/**
* 将传入的字符串参数转化成制定的数据类型,如果格式不匹配则返回null
* @param <T>
* @param param 要转换的参数字符串
* @param clas 转换的目标CLASS
* @return
*/
private static <T extends Serializable> T convert(String param, Class clas) {
if (param == null || param == "" || clas == null) return null;
String type = clas.getName();// 获得要转换的数据类型名称
if (type.equals("java.lang.String"))
return (T) param;
try {// 根据不同类型的属性,返回不同的结果,如果出现异常,则返回null
if (type.equals("java.util.Date")) {
return (T) new Date(java.sql.Date.valueOf(param)
.getTime());
}
if (type.equals("java.sql.Date")) {
return (T) java.sql.Date.valueOf(param);
}
if (type.equals("java.sql.Timestamp")) {
return (T) java.sql.Timestamp.valueOf(param);
}
if (type.equals("java.lang.Char")) {
return (T) Character.valueOf(param.charAt(0));
}
if (type.equals("java.lang.Integer") || type.equals("int")) {
return (T) new Integer(param);
}
if (type.equals("java.lang.Double") || type.equals("double")) {
return (T) new Double(param);
}
if (type.equals("java.lang.Float") || type.equals("float")) {
return (T) new Float(param);
}
if (type.equals("java.lang.Byte") || type.equals("boolean")) {
return (T) new Boolean(param);
}
if (type.equals("java.lang.Short") || type.equals("short")) {
return (T) new Short(param);
}
if (type.equals("java.lang.Long") || type.equals("long")) {
return (T) new Long(param);
}
if (type.equals("java.lang.Boolean") || type.equals("boolean")) {
return (T) new Boolean(param);
}
} catch (Exception e) {
}
return null;
}
/**
* 将传入的字符串数组参数转化成指定的数据类型的数组,如果格式不匹配则返回null
* @param param 要转换的参数字符串
* @param elementClass 转换的目标CLASS,一定是数组中元素的Class,而不是数组的Class
* @return
*/
private static Object convertArray(String[] param, Class elementClass) {
if (param == null || elementClass == null)
return null;
String type = elementClass.getName();// 获得要转换的数据类型名称
Object array = Array.newInstance(elementClass, param.length);// 创建指定类型的数组对象
if (type.equals("java.lang.String")) {
return param;
}
if (type.equals(List.class.getName())) {
List list = Arrays.asList(param);//如果属性是List集合,则将字符串数组转换为LIst集合
return list;
}
try {// 根据不同类型的属性,返回不同的结果,如果出现异常,则返回null
if (type.equals("java.util.Date") || type.equals("java.sql.Date")
|| type.equals("java.sql.Timestamp")) {
for (int i = 0; i < param.length; i++) {
Array.set(array,i, convert(param[i],elementClass));
}
return array;
}
if (type.equals("java.lang.Character")) {
for (int i = 0; i < param.length; i++) {
Array.setChar(array, i, param[i].charAt(i));
}
return array;
}
if (type.equals("java.lang.Integer") || type.equals("int")) {
for (int i = 0; i < param.length; i++) {
Array.setInt(array, i, Integer.parseInt(param[i]));
}
return array;
}
if (type.equals("java.lang.Double") || type.equals("double")) {
for (int i = 0; i < param.length; i++) {
Array.setDouble(array, i, Double.parseDouble(param[i]));
}
return array;
}
if (type.equals("java.lang.Float") || type.equals("float")) {
for (int i = 0; i < param.length; i++) {
Array.setFloat(array, i, Float.parseFloat(param[i]));
}
return array;
}
if (type.equals("java.lang.Byte") || type.equals("byte")) {
for (int i = 0; i < param.length; i++) {
Array.setByte(array, i, Byte.parseByte(param[i]));
}
return array;
}
if (type.equals("java.lang.Short") || type.equals("short")) {
for (int i = 0; i < param.length; i++) {
Array.setShort(array, i, Short.parseShort(param[i]));
}
return array;
}
if (type.equals("java.lang.Long") || type.equals("long")) {
for (int i = 0; i < param.length; i++) {
Array.setLong(array, i, Long.parseLong(param[i]));
}
return array;
}
if (type.equals("java.lang.Boolean") || type.equals("boolean")) {
for (int i = 0; i < param.length; i++) {
Array.setBoolean(array, i, Boolean.parseBoolean(param[i]));
}
return array;
}
} catch (Exception e) {
}
return null;
}
public static void main(String[] ss) throws SQLException, InstantiationException, IllegalAccessException {
BaseDB db=new BaseDB();
List list=db.queryMap("select * from Dept", null);
List objList = TransBean.populate(Dept.class,list);
System.out.println(objList);
}
}
第二步:添加查询条件
分页中还需要有另外两个数据:1)总共有多少条;2)总共有多少页;这些数据和当前是第几页,页面显示的数据等信息都要做页面显示,需要一个数据载体类
PageBean:
public class PageBean<T> {
private int pageNo=1;//当前页数,默认为1
private int pageSize=10;//每页行数
private int rowCount;//共有行数
private int totalPage;//共有页数
private int startIndex=0;//limit起始索引
private String[] factor;//查询条件数组
private List<T> data;//查询的数据
...
}
deptPage.jsp
<%--
Created by IntelliJ IDEA.
User: Justice
Date: 2020/8/21
Time: 7:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>分页</title>
<script src="static/js/jquery-3.5.1.min.js"></script>
<script src="static/js/myjs.js"></script>
<style>
#countdiv{
display:inline-block;
}
#countdiv a{
display: inline-block;
text-decoration: none;
margin-left: 2px;
text-align:center;
width:40px;
height:30px;
line-height: 30px;
background-color: antiquewhite;
}
</style>
</head>
<body>
<form id="form" method="post">
部门名称:<input name="dname" id="dname">
起始时间:<input type="date" id="createTime">
<input type="button" value="查询" id="btn">
</form>
<hr>
<table width="600px">
<tr>
<th>部门编号</th>
<th>部门名称</th>
<th>创建日期</th>
</tr>
<tbody id="tb"></tbody>
</table>
<script>
let pageBean=new Object();
pageBean.pageSize=6;
function search(num) {
pageBean.pageNo = num;
pageBean.factor=[];//添加条件前将原来条件清空
if($("#dname").val()!=null&&$("#dname").val()!=""){
pageBean.factor.push(" dname like '%"+$("#dname").val()+"%'");
}
if($("#createTime").val()!=null&&$("#createTime").val()!=""){
pageBean.factor.push(" createTime >= '"+$("#createTime").val()+"'");
}
$.ajax({
url:"/deptController/findByPage",
type:"post",
data:pageBean,//将pageBean直接作为
success:function(page){
pageBean=page;//将返回的pageBean赋值给本页的pageBean
pageBean.factor=[];//如果没有给后台传查询因子,则该项为null,就不能用push添加内容
$("#tb").empty();//清空表格
addTab("tb",pageBean.data,["deptno","dname","createTime"])//将数据添加到表格
$("#num").html(pageBean.pageNo);//设置当前页数显示
$("#totalPage").html(pageBean.totalPage);//显示总共页数
//-----------设置上一页、下一页是否显示---------------
if(pageBean.pageNo==1){
$("#prev").hide();
}else{
$("#prev").show();
}
if(pageBean.pageNo==pageBean.totalPage){
$("#next").hide();
}else{
$("#next").show();
}
//--------------------------
$("#countdiv").empty();//清空导航页块
for(let i=1;i<=pageBean.totalPage;i++){//添加导航页块
$("#countdiv").append($("<a href='javascript:search("+i+")'>"+i+"</a>"));
}
},
dataType:"json"
})
}
$(function(){//页面加载完成后就调用search函数
search(1);
$("#btn").click(function(){//跟按钮注册点击时调用search函数
search(1);
})
})
</script>
当前是第<span id="num"></span>页 总共有<span id="totalPage"></span>页<br>
<a id="prev" href="javascript:search(pageBean.pageNo-1)">上一页</a>
<div id="countdiv">
</div>
<a id="next" href="javascript:search(pageBean.pageNo+1)">下一页</a>
<hr>
</body>
</html>
DeptDaoImpl:
@Override
public void findByPage(PageBean page) throws SQLException {
//-------计算行数和页数-----------
String sql="select count(*) from dept where 1=1 ";
String factor="";
String[] condition=page.getFactor();
if(condition!=null&&condition.length>0) {
for (String cod : condition) {
factor += " and " + cod;
}
}
List<List> lists = BaseDB.query(sql + factor);
int count= ((Long) lists.get(0).get(0)).intValue();//查询获得总行数
page.setRowCount(count);//设置总行数
page.setTotalPage();//计算和设置总页数
//--以下和第一次的基本相同,就是按条件查询数据,但这次是设置到pageBean的data中----
sql="select deptno,dname,createTime from dept where 1=1 %s limit ?,? ";
sql = String.format(sql, factor);//将查询条件添加到%s占位符处
System.out.println(sql);
try {
List<Map> dlist=BaseDB.queryMap(sql,
(page.getPageNo()-1)*page.getPageSize(),page.getPageSize());
List<Dept> list=TransBean.populate(Dept.class,dlist);
page.setData(list);//将查询的数据设置到pageBean中
} catch (SQLException e) {
e.printStackTrace();
}
}
DeptServlet
@WebServlet(value = "/deptController/*")
public class DeptServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri=request.getRequestURI();
System.out.println(uri);
String method=uri.substring(uri.lastIndexOf("/")+1);
String target=null;
switch(method){
case "findByPage":target=findByPage(request,response);break;
case "findByPageBean":target=findByPageBean(request,response);break;
}
if(target!=null){
request.getRequestDispatcher(target).forward(request,response);
}
}
private String findByPage(HttpServletRequest request, HttpServletResponse response) {
PageBean pageBean=new PageBean();
try {
//BeanUtils.populate(pageBean,request.getParameterMap());
TransBean.populate(pageBean,request.getParameterMap());
System.out.println(pageBean);
deptDao.findByPage(pageBean);
String jsonStr=JSON.toJSONString(pageBean);
System.out.println(jsonStr);
output(response,jsonStr );
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
由于BeanUtils中没有将参数”XXX[ ]”名进行转换的方法,可以自己写一个通用的转换方法,将这种数据类型也一并转换,也可以完成从数据库数据List
package com.aaa.util;
import com.aaa.dao.BaseDB;
import com.aaa.entity.Dept;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.*;
public class TransBean {
/**
* 根据request传来的参数Map,和指定的实体Bean的属性进行比较,将二者名称相同的参数转换成属性类型的值,
* 并调用相应的set方法给Bean的属性赋值, *
* @param map=request.getParameterMap();
* @param obj 要填充的对象 *
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void populate(Object obj,Map<String,String[]> map){
Set<String> keySet=map.keySet();
Class objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
try {
for(Field field:fields){
String propName=field.getName();
if(field.getType().isArray()
||field.getType().getName().equals("java.util.List")){
if (map.get(propName) != null||map.get(propName + "[]") != null) {
//如果数组中有多个元素
//如果参数是数组,则其名称可能为"xxx[]"(ajax传来的json对象参数),所以要将后面的“[]”去掉再和属性名进行比较
field.setAccessible(true);
field.set(obj, convertArray(map.get(propName) == null ?
map.get(propName + "[]") : map.get(propName),
field.getType().getComponentType()));
//将字符串数组转换成该属性的数组类型并赋值getComponentType():获得数组中元素的类型
}
}else {
if (map.get(propName) != null && map.get(propName).length == 1 && map.get(propName)[0] != null) {//如果值数组只有一个元素并且不为空
field.setAccessible(true);//设置属性可访问
field.set(obj, convert(map.get(propName)[0], field.getType()));//将字符串转换成该属性的类型并赋值
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static List populate(Class objClass,List<Map> listMapData){
if(listMapData==null||listMapData.size()==0)return null;
List list=new ArrayList();
Field[] fields = objClass.getDeclaredFields();//获得该类型所有声明的属性
try {
for(Map map:listMapData) {
Object obj=objClass.newInstance();//创建实体类对象
for (Field field : fields) {//遍历所有属性
String propName = field.getName();//获得当前属性的名称
if (map.containsKey(propName)){//如果map中包含该属性
field.setAccessible(true);//设置属性可访问
field.set(obj,convert(map.get(propName)==null?"":map.get(propName).toString(),field.getType()));
//给该属性设置值(这里将所有类型的值都转换成string,然后再转换成该属性对应的类型)
}
}
list.add(obj);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
/**
* 将传入的字符串参数转化成制定的数据类型,如果格式不匹配则返回null
*
* @param <T>
* @param param 要转换的参数字符串
* @param clas 转换的目标CLASS
* @return
*/
private static <T extends Serializable> T convert(String param, Class clas) {
if (param == null || param == "" || clas == null) return null;
String type = clas.getName();// 获得要转换的数据类型名称
if (type.equals("java.lang.String"))
return (T) param;
try {// 根据不同类型的属性,返回不同的结果,如果出现异常,则返回null
if (type.equals("java.util.Date")) {
return (T) new Date(java.sql.Date.valueOf(param)
.getTime());
}
if (type.equals("java.sql.Date")) {
return (T) java.sql.Date.valueOf(param);
}
if (type.equals("java.sql.Timestamp")) {
return (T) java.sql.Timestamp.valueOf(param);
}
if (type.equals("java.lang.Char")) {
return (T) Character.valueOf(param.charAt(0));
}
if (type.equals("java.lang.Integer") || type.equals("int")) {
return (T) new Integer(param);
}
if (type.equals("java.lang.Double") || type.equals("double")) {
return (T) new Double(param);
}
if (type.equals("java.lang.Float") || type.equals("float")) {
return (T) new Float(param);
}
if (type.equals("java.lang.Byte") || type.equals("boolean")) {
return (T) new Boolean(param);
}
if (type.equals("java.lang.Short") || type.equals("short")) {
return (T) new Short(param);
}
if (type.equals("java.lang.Long") || type.equals("long")) {
return (T) new Long(param);
}
if (type.equals("java.lang.Boolean") || type.equals("boolean")) {
return (T) new Boolean(param);
}
} catch (Exception e) {
}
return null;
}
/**
* 将传入的字符串数组参数转化成指定的数据类型的数组,如果格式不匹配则返回null
*
* @param param 要转换的参数字符串
* @param elementClass 转换的目标CLASS,一定是数组中元素的Class,而不是数组的Class
* @return
*/
private static Object convertArray(String[] param, Class elementClass) {
if (param == null || elementClass == null)
return null;
String type = elementClass.getName();// 获得要转换的数据类型名称
Object array = Array.newInstance(elementClass, param.length);// 创建指定类型的数组对象
if (type.equals("java.lang.String")) {
return param;
}
if (type.equals(List.class.getName())) {
List list = Arrays.asList(param);//如果属性是List集合,则将字符串数组转换为LIst集合
return list;
}
try {// 根据不同类型的属性,返回不同的结果,如果出现异常,则返回null
if (type.equals("java.util.Date") || type.equals("java.sql.Date")
|| type.equals("java.sql.Timestamp")) {
for (int i = 0; i < param.length; i++) {
Array.set(array,i, convert(param[i],elementClass));
}
return array;
}
if (type.equals("java.lang.Character")) {
for (int i = 0; i < param.length; i++) {
Array.setChar(array, i, param[i].charAt(i));
}
return array;
}
if (type.equals("java.lang.Integer") || type.equals("int")) {
for (int i = 0; i < param.length; i++) {
Array.setInt(array, i, Integer.parseInt(param[i]));
}
return array;
}
if (type.equals("java.lang.Double") || type.equals("double")) {
for (int i = 0; i < param.length; i++) {
Array.setDouble(array, i, Double.parseDouble(param[i]));
}
return array;
}
if (type.equals("java.lang.Float") || type.equals("float")) {
for (int i = 0; i < param.length; i++) {
Array.setFloat(array, i, Float.parseFloat(param[i]));
}
return array;
}
if (type.equals("java.lang.Byte") || type.equals("byte")) {
for (int i = 0; i < param.length; i++) {
Array.setByte(array, i, Byte.parseByte(param[i]));
}
return array;
}
if (type.equals("java.lang.Short") || type.equals("short")) {
for (int i = 0; i < param.length; i++) {
Array.setShort(array, i, Short.parseShort(param[i]));
}
return array;
}
if (type.equals("java.lang.Long") || type.equals("long")) {
for (int i = 0; i < param.length; i++) {
Array.setLong(array, i, Long.parseLong(param[i]));
}
return array;
}
if (type.equals("java.lang.Boolean") || type.equals("boolean")) {
for (int i = 0; i < param.length; i++) {
Array.setBoolean(array, i, Boolean.parseBoolean(param[i]));
}
return array;
}
} catch (Exception e) {
}
return null;
}
public static void main(String[] ss) throws SQLException, InstantiationException, IllegalAccessException {
BaseDB db=new BaseDB();
List list=db.queryMap("select * from Dept", null);
List objList = TransBean.populate(Dept.class,list);
System.out.println(objList);
}
}
4、ajax文件上传
文件上传前端代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="/static/js/jquery-3.3.1.js"></script>
<script>
$(function(){
$("#btn").click(function(){
alert(1111);
$.ajax({
url:"/deptServlet/uploadFile",
data:new FormData($("#form")[0]),
type:"post",
contentType: false,//不去设置请求头文件
processData: false,//不要去处理发送的数
success:function(result){
alert(result);
},
dataType:"text"
});
});
})
</script>
</head>
<body>
<form id="form" method="post" enctype="multipart/form-data">
部门名称:<input name="dname" id="dname"><span id="deptmsg"></span><br>
创建时间:<input type="date" name="createTime"><br>
上传文件:<input type="file" name="deptimg" accept="image/gif, image/jpeg">图片<br>
<input type="button" value="添加" id="btn">
</form>
</body>
</html>
后端代码和前面的相同
private String uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Map<String, String[]> map = request.getParameterMap();
Dept dept=new Dept();
try {
BeanUtils.populate(dept,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(dept);
DeptDao dao=new DeptDaoImpl();
dao.addDept(dept);
//------------下面是文件上传代码-----------------
Part part=request.getPart("deptimg");
String header=part.getHeader("Content-Disposition");
String suffix=header.substring(header.lastIndexOf("."),header.length()-1);
String filename= UUID.randomUUID()+suffix;
part.write(filename);
ajaxOutput(response,"添加成功");
return null;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/75548.html