4.2 使用AJAX实现分页
4.2.1 需求
需要将分页数据通过ajax的方式进行分页,实现只变更部分数据的功能.
4.2.2 实现原理
1.设置Servlet的response的格式为application/json,
2.借助于jackson库的ObjectMapper类将分页数据转换为json字符串的形式.
3.使用response的writer写出内容.
4.在前端jsp页面接收数据,并将数据格式化为html文本,写入到指定html元素中.
4.2.3 步骤
4.2.3.1 改写servlet
原先是通过设置request的域属性,将页面数据传到jsp,使用jtsl引用.
现在是将数据转换为json字符串.传给jsp页面,然后由ajax处理.
<body>
<h1 style="text-align: center">购物商城</h1>
<hr>
<div style="text-align: center">
名称:<input id="strName" type="text" name="strName">
<button id="searchBtn" class="btn btn-default">搜索</button>
</div>
<br>
<div id="content"></div>
<div>
<span id="start"></span>/<span id="end"></span> <a href="" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >首页</a> <a
href="" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >上一页</a> <a href="javascript:nextBtn();" target="_blank" rel="external nofollow" >下一页</a> <a href="" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >尾页</a>
</div>
</body>
@Override
public List<Goods> queryGoodsAll(int pageIndex, int pageSize, String strName) {
int start = (pageIndex - 1) * pageSize + 1;
int end = pageIndex * pageSize;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "";
List<Goods> list = new ArrayList<Goods>();
Goods goods = null;
try {
conn = DBHelper.getConn();
sql ="select b.* from(select a.*,rownum as rid from( select * from mvc_good where gname like '%"+strName+"%')a)b where b.rid between "+start+" and "+end+"";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
goods = new Goods(rs.getInt(1), rs.getString(2), rs.getFloat(3),rs.getInt(4), rs.getString(5), rs.getString(6));
list.add(goods);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.myClose(conn, ps, rs);
}
return list;
}
@Override
public int getGoodsCount(String strName) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
int count = 0;// 保存表的总记录数
try {
conn = DBHelper.getConn();
String sql = "select count(*) from mvc_good where gname like '%"+strName+"%'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(conn, ps, rs);
}
return count;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//实例化
IGoodsBiz igb = new GoodsBizImpl();
//定义变量存储页码以及每一夜显示的数据
int pageIndex = 1;
int pageSize = 4;
int pageMax = 0;//存储最大页码
//当点击分页区域的下一页超链接时,获取这个参数
String pIndex = request.getParameter("pageIndex");
//判断,只有你点击了下一页 才将pIndex赋值给pageIndex
if (null != pIndex) {
pageIndex = Integer.valueOf(pIndex);
}
String strName = request.getParameter("strName");
if (strName == null) {
strName = "";
}
//根据dao求出总记录数
int count = igb.getGoodsCount(strName);
pageMax = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
List<Goods> listGoods = igb.queryGoodsAll(pageIndex, pageSize, strName);
PrintWriter out = response.getWriter();// 获取输出对象
Map<String, Object> maps = new HashMap<String, Object>();// 创建了集合
maps.put("listGoods", listGoods);
maps.put("pageIndex", pageIndex);
ObjectMapper mapper = new ObjectMapper();
String writeValueAsString = mapper.writeValueAsString(maps);
out.write(writeValueAsString);
out.flush();
out.close();
}
2.引入jQuery库,利用AJAX技术实现分页
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
let pageIndex = 1;
let path = "${pageContext.request.servletContext.contextPath}";
$(function(){
myload("");
$("#searchBtn").click(function(){
let searchName = $("#strName").val();
if(!searchName){
alert("请输入关键词");
return;
}
myload("searchName");
})
})
function myload(strName){
$.post(path+"/adminIndex.do",{"pageIndex":pageIndex,"strName":strName},function(msg){
let map =$.parseJSON(msg);
let str = "";
str+="<table class='table table-bordered table-responsive' width='100%' cellpadding='0' cellspacing='0'>";
str+="<tr class='list-group-item-danger'>";
str+="<th>商品编号</th>";
str+="<th>商品名称</th>";
str+="<th>商品价格</th>";
str+="<th>商品库存</th>";
str+="<th>商品描述</th>";
str+="<th>商品图片</th>";
str+="<th>商品操作</th>";
str+="</tr>";
$.each(map.listGoods,function(index,object){
str+="<tr>";
str+="<td>"+object.gid+"</td>";
str+="<td>"+object.gname+"</td>";
str+="<td>"+object.gprice+"</td>";
str+="<td>"+object.gstock+"</td>";
str+="<td>"+object.ginfo+"</td>";
str+="<td><img width='80' height='60' src ='"+object.gpath+"'></td>";
str+="<td><button class='btn btn-default'>删除</button><button class='btn btn-default'>修改</button></td>";
str+="</tr>";
})
str+="</table>";
$("#content").html(str);
$("#start").html(pageIndex);
$("#end").html(pageMax);
});
}
function nextBtn(){
if(pageIndex>=pageMax){
pageIndex=pageMax;
return;
}else{
pageIndex++;
}
myload();
}
</script>