easyui 的datagrid点击第二页时显示的内容和第一页相同

easyui 的datagrid点击第二页时显示的内容和第一页相同
后台也将total和所有的数据都返回给datagrid了。
这个问题这主要是没有给datagrid添加翻页的出发的事件。
完整的datagrid(HTML+easyui+Jquery+MVC+Mybatis)实现CRUD如下:

HTML: —– *
*
新增快递运输信息 编辑快递运输信息 删除快递运输信息 查询快递运输信息 退出

JS:

/**
* Created by Administrator on 2017/5/19 0019.
*/
/**
* Created by Administrator on 2017/5/17 0017.
*/
// *******************全局变量**************************************
$(function(){
//使用javascript创建datagrid插件
createDatagrid();
//将数据库中的数据加载出来传到前台页面的datagrid
transportMsgData();

//点击新建按钮,弹出新建的弹窗
$("#addMsg").click(function(){
    //关闭所有的弹窗
    closeAllDialogs();
    //加载快递单ID信息
    loadTrackIds();
    //弹出增加弹窗
    $("#dd_add").dialog({closed:false});
});

//点击新增弹窗的确定按钮
$('#addConfirm').click(function(){
    //执行新增快递运输信息的方法
    addNewTransport();
    //关闭弹窗
    $("#dd_add").dialog({closed:true});
    //刷新当前页面
    window.location.reload();
});

//点击修改按钮,弹出修改的弹窗
$("#editMsg").click(function(){
    //关闭所有的弹窗
    closeAllDialogs();
    //获取datagrid中被选中的行
    var selected = $('#dg').datagrid('getSelected');
    //如果选中的行不为空
    if(selected != null){
        //将选中的参数传给编辑表单对应的输入框
        setEditDialogFormTransportValue(selected);
        //弹出增加弹窗
        $("#dd_update").dialog({closed:false});
    }else{
        //如果选中的行为空,提示用户先选中一行
        $.messager.show({
            title:'修改快递运费信息',
            msg:'请先选中一条记录',
            timeout:3000,
            showType:'slide'
        });
    }
});

//点击编辑弹窗的确定按钮
$('#editConfirm').click(function(){
    //执行编辑快递单信息的方法
    editTransportMsg();
    //关闭弹窗
    $("#dd_edit").dialog({closed:true});
    //刷新当前页面
    window.location.reload();
});

//点击删除按钮,弹出修改的弹窗
$("#deleteMsg").click(function(){
    //关闭所有的弹窗
    closeAllDialogs();
    //获取datagrid中被选中的行
    var selected = $('#dg').datagrid('getSelected');
    //如果选中的行不为空
    if(selected != null){
        //将选中的参数传给编辑表单对应的输入框
        if(!judgeInputIsEmpty(selected.transport_id)) {
            $('#deleteForm input[name="transport_id"]').val(selected.transport_id);
        }
        //弹出增加弹窗
        $("#dd_delete").dialog({closed:false});
    }else{
        //如果选中的行为空,提示用户先选中一行
        $.messager.show({
            title:'删除物流路线图信息',
            msg:'请先选中一条记录',
            timeout:3000,
            showType:'slide'
        });
    }
});

//点击删除弹窗的确定按钮
$('#deleteConfirm').click(function(){
    //执行删除物流路线信息的方法
    deleteTransport();
    //关闭弹窗
    $("#dd_delete").dialog({closed:true});
    //刷新当前页面
    window.location.reload();
});

//点击查询弹窗的确定按钮
$('#searchConfirm').click(function(){
    //执行查询物流路线图信息的方法
    searchTransport();
    //关闭弹窗
    $("#dd_search").dialog({closed:true});
});

//点击查询按钮,弹出查询的弹窗
$("#searchMsg").click(function(){
    //关闭所有的弹窗
    closeAllDialogs();
    //设置查询窗口默认样式
    setSearchDialogFormTransportValue();
    //弹出查询弹窗
    $("#dd_search").dialog({closed:false});
});

//新增表单中添加站点的按钮
$('#addForm input.addStation').click(function () {
    $('#addForm tbody').append(''+
        ''+
        '');
});

//新增表单中添加站点的按钮
$('#addForm input.deleteStation').click(function () {
    //删除table里的最后一个站点
    $('#addForm tr.station:last').remove();
});

});
//使用javascript创建datagrid插件
function createDatagrid(){
(‘#dg’).datagrid({  
        toolbar:’#tb’,  
        pagination:true,  
        pageSize:15,  
        pagination:true,  
        pageNumber:1,  
        pageList:[15,30,45],  
        height: 500,  
        singleSelect:true,  
        loadMsg: ‘正在加载数据…’,  
        columns:[[  
            {field:’transport_id’,title:’快递运输id’,width:60,align:’center’,hidden:true},  
            {field:’transport_startStation’,title:’快递运输始发站’,width:120,align:’center’},  
            {field:’transport_nextStation’,title:’快递运输下一站’,width:100,align:’center’},  
            {field:’transport_date’,title:’快递运输日期’,width:150,align:’center’,  
                formatter:function(value,row,index){  
                    var date = new Date(value);  
                    return date.toLocaleDateString()+” “+date.toLocaleTimeString();  
                }},  
            {field:’track_id’,title:’快递单id’,width:60,align:’center’},  
            {field:’client_id’,title:’寄件人id’,width:100,align:’center’,hidden:true},  
            {field:’recipients_id’,title:’收件人id’,width:100,align:’center’,hidden:true},  
            {field:’package_id’,title:’包裹id’,width:100,align:’center’,hidden:true},  
            {field:’employee_id’,title:’员工id’,width:100,align:’center’,hidden:true},  
            {field:’track_date’,title:’快递单日期’,width:100,align:’center’,  
                formatter:function(value,row,index){  
                    var date = new Date(value);  
                    return date.toLocaleDateString();  
                },hidden:true}  
        ]]  
    });
(‘#dg’).datagrid(‘getPager’).pagination({
onSelectPage:function(pageNumber,pageSize) {
var num = pageNumber;
var size = pageSize;
.ajax({  
                url:’/loadTransportMsgData.transport’,  
                type:’post’,  
                data:{‘page’: num,’rows’: size},  
                dataType:’json’,  
                async : false,  
                success:function(data){  
                    //测试数据是否可以正常显示  
                    //console.log(data);
(‘#dg’).datagrid(‘loadData’, data);
},
error:function(data){
.messager.show({  
                        title:’加载快递运输信息’,  
                        msg:’加载失败’,  
                        timeout:3000,  
                        showType:’slide’  
                    });  
                }  
            }) ;  
        }  
    });  
}  
//将数据库中的数据加载出来传到前台页面的datagrid的方法  
function transportMsgData(){  
    //debugger;  
    var p =
(‘#dg’).datagrid(‘getPager’);
//获得datagrid的page和size参数
var num = p.data(‘pagination’).options.pageNumber;
var size = p.data(‘pagination’).options.pageSize;
if (p)
{
.ajax({  
            url:’/loadTransportMsgData.transport’,  
            type:’post’,  
            data:{‘page’: num,’rows’: size},  
            dataType:’json’,  
            async : false,  
            success:function(data){  
                //测试数据是否可以正常显示  
                //console.log(data);
(‘#dg’).datagrid(‘loadData’, data);
},
error:function(data){
.messager.show({  
                    title:’加载物流路线图信息’,  
                    msg:’加载失败’,  
                    timeout:3000,  
                    showType:’slide’  
                });  
            }  
        }) ;  
    }else{
.messager.show({
title:’加载物流路线图信息’,
msg:’加载失败’,
timeout:3000,
showType:’slide’
});
}
}

//加载快递单ID信息
function loadTrackIds(){
.ajax({  
        url:’/loadTrackIdsData.transport’,  
        type:’post’,  
        data:{},  
        dataType:’text’,  
        async : false,  
        success:function(data){  
            //在浏览器控制台查看返回的数据  
            //console.log(“stationIds”+data)  
            //取出所有的stationIds  
            var trackIds = new Array();  
            trackIds = data.split(‘,’);  
            //在浏览器控制台查看返回的数据  
            //console.log(“employeeIds”+employeeIds);  
            if(trackIds != null){  
                //删除新增表单站点下拉框的所有选项
(‘select[name=”track_id”]’).empty();
//新增表单站点下拉框的添加选项
for(var id = 0; id < trackIds.length; id ++){
(‘select[name=”track_id”]’).append(‘‘+trackIds[id]+’‘);  
                }  
            }  
        },  
        error:function(data){
.messager.show({
title:’加载快递单ID信息’,
msg:’加载失败’,
timeout:3000,
showType:’slide’
});
}
}) ;
}

//执行新增快递运输信息的方法
function addNewTransport(){
//获取增加表单的参数
var transport_startStation = (‘#addForm input[name=”transport_startStation”]’).val();  
    var track_id =
(‘#addForm select[name=”track_id”]’).val();
var transport_nextStation = (‘#addForm input[name=”transport_nextStation”]’).val();  
    //将表单内容通过ajax传给后台
.ajax({
url:’/addTransportData.transport’,
type:’post’,
data:{
transport_startStation:transport_startStation,track_id:track_id,
transport_nextStation:transport_nextStation
},
dataType:’text’,
async : false,
success:function(data){
//查看data的值
//console.log(data);
//window.alert(data.msg);
if(data == ‘true’){
.messager.show({  
                    title:’快递运输信息’,  
                    msg:’新增快递运输信息成功!’,  
                    timeout:3000,  
                    showType:’slide’  
                });  
            }else{
.messager.show({
title:’快递运输信息’,
msg:’新增快递运输信息失败!(后台操作错误)’,
timeout:3000,
showType:’slide’
});
}
},
error:function(data){
$.messager.show({
title:’快递运输信息’,
msg:’新增增快递运输信息失败!(可能是数据格式错误)’,
timeout:3000,
showType:’slide’
});
}
}) ;
}

//将选中的参数传给编辑表单对应的输入框
function setEditDialogFormTransportValue(obj){
loadTrackIds();
(‘#editForm input[name=”transport_startStation”]’).val(obj.transport_startStation);(‘#editForm select[name=”track_id”] option[value=”’+obj.track_id+’”]’).attr(“selected”, true);
(‘#editForm select[name=”track_id”] option[value=”’+obj.track_id+’”]’).siblings().attr(“selected”, false);(‘#editForm input[name=”transport_id”]’).val(obj.transport_id);
$(‘#editForm input[name=”transport_nextStation”]’).val(obj.transport_nextStation);
}

//执行编辑快递运输信息的方法
function editTransportMsg(){
//获取增加表单的参数
var transport_id = (‘#editForm input[name=”transport_id”]’).val();  
    var transport_startStation =
(‘#editForm input[name=”transport_startStation”]’).val();
var transport_nextStation = (‘#editForm input[name=”transport_nextStation”]’).val();  
    var track_id =
(‘#editForm select[name=”track_id”]’).val();
//将表单内容通过ajax传给后台
.ajax({  
        url:’/editTransportData.transport’,  
        type:’post’,  
        data:{  
            transport_startStation:transport_startStation,track_id:track_id,  
            transport_nextStation:transport_nextStation,transport_id:transport_id  
        },  
        dataType:’text’,  
        async : false,  
        success:function(data){  
            //查看data的值  
            //console.log(data);  
            //window.alert(data.msg);  
            if(data == ‘true’){
.messager.show({
title:’快递运输信息’,
msg:’修改快递运输信息成功!’,
timeout:3000,
showType:’slide’
});
}else{
.messager.show({  
                    title:’快递运输信息’,  
                    msg:’修改快递运输信息失败!(后台操作错误)’,  
                    timeout:3000,  
                    showType:’slide’  
                });  
            }  
        },  
        error:function(data){
.messager.show({
title:’快递运输信息’,
msg:’修改快递运输信息失败!(可能是数据格式错误)’,
timeout:3000,
showType:’slide’
});
}
}) ;
}
//执行删除站点信息的方法
function deleteTransport(){
//获取增加表单的参数
var transport_id = (‘#deleteForm input[name=”transport_id”]’).val();  
    //将表单内容通过ajax传给后台
.ajax({
url:’/deleteTransportData.transport’,
type:’post’,
data:{transport_id:transport_id},
dataType:’text’,
async : false,
success:function(data){
//查看data的值
//console.log(data);
//window.alert(data.msg);
if(data == ‘true’){
.messager.show({  
                    title:’快递运输信息’,  
                    msg:’删除快递运输信息成功!’,  
                    timeout:3000,  
                    showType:’slide’  
                });  
            }else{
.messager.show({
title:’快递运输信息’,
msg:’删除快递运输信息失败!(后台操作错误)’,
timeout:3000,
showType:’slide’
});
}
},
error:function(data){
$.messager.show({
title:’快递运输信息’,
msg:’删除快递运输信息失败!(可能是数据格式错误)’,
timeout:3000,
showType:’slide’
});
}
}) ;
}

//设置查询窗口默认样式
function setSearchDialogFormTransportValue(){
loadTrackIds();
$(‘#searchForm select[name=”track_id”]’).prepend(‘‘);
}

//执行查询快递运输信息的方法
function searchTransport(){
//获取增加表单的参数
var transport_startStation = (‘#editForm input[name=”transport_startStation”]’).val();  
    var transport_nextStation =
(‘#editForm input[name=”transport_nextStation”]’).val();
var track_id = (‘#editForm select[name=”track_id”]’).val();  
    var p =
(‘#dg’).datagrid(‘getPager’);
//获得datagrid的page和size参数
var num = p.data(‘pagination’).options.pageNumber;
var size = p.data(‘pagination’).options.pageSize;
transport_startStation = ‘%’ + transport_startStation + ‘%’;
transport_nextStation = ‘%’ + transport_nextStation + ‘%’;
if(p){
//将表单内容通过ajax传给后台
.ajax({  
            url:’/searchTransportData.transport’,  
            type:’post’,  
            data:{  
                num:num,size:size,  
                transport_startStation:transport_startStation,track_id:track_id,  
                transport_nextStation:transport_nextStation  
            },  
            dataType:’json’,  
            async : false,  
            success:function(data){  
                //测试数据是否可以正常显示  
                //console.log(data);
(‘#dg’).datagrid(‘loadData’, data);
},
error:function(data){
$.messager.show({
title:’快递运输信息’,
msg:’查询快递运输信息失败!(可能是数据格式错误)’,
timeout:3000,
showType:’slide’
});
}
}) ;
}
}

servlet:

package com.wzb.servlet;

import com.wzb.dao.ServletMethodsDao;
import com.wzb.impl.LogisticsPathImpl;
import com.wzb.impl.TransportImpl;
import com.wzb.model.LogisticsPathViewModel;
import com.wzb.model.TransportViewModel;
import com.wzb.utils.JsonData;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by Administrator on 2017/5/17 0017.
*/
public class TransportMsgServlet extends HttpServlet implements ServletMethodsDao {
//设置私有成员变量保存分页的单页容纳记录数
private int pageSize = 0;
//设置私有成员变量保存分页的页数
private int pageNum = 0;
//设置私有成员变量保存总记录数
private int total = 0;

//setter方法
public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
}

public void setPageNum(int pageNum) {
    this.pageNum = pageNum;
}

public void setTotal(int total) {
    this.total = total;
}

//getter方法
public int getPageNum() {
    return pageNum;
}

public int getPageSize() {
    return pageSize;
}

public int getTotal() {
    return total;
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //设置编码格式
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    //获取不同的请求路径
    String methodURI = req.getRequestURI();
    //由请求路径获得请求的方法
    String method = null;
    try {
        //去除“/”和".*"的部分,例如“/allUsersMsg.message”,只留“allUsersMsg”
        String[] str1 = methodURI.split("\\.");
        String[] str2 = str1[0].split("/");
        method = str2[1];
    } catch (Exception e) {
        e.printStackTrace();
    }
    //如果action是“login.login”,method=login
    if (method != null && "loadTransportMsgData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            loadData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (method != null && "addTransportData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            insertData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (method != null && "editTransportData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            updateData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }else if (method != null && "deleteTransportData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            deleteData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }else if (method != null && "searchTransportData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            searchData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }else if (method != null && "loadTrackIdsData".equals(method)) {
        try {
            //如果是登陆页面提交的表单就交给下面方法
            loadTrackIdsData(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 加载所有的快递单ID
 * @param request
 * @param response
 * @throws Exception
 */
private void loadTrackIdsData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //调用操作方法获取所有的stationIds
    List ids = (List)transportImpl.getAllTrackIds();
    //设置一个字符串变量保存所有的stationId
    String str = "";
    for (Integer id : ids){
        str = str + id;
        str = str + ",";
    }
    str = str.substring(0, str.length() - 1);
    //打印IDs
    //System.out.println("str : "+str);
    //使用PrintWriter向ajax传递值
    PrintWriter out = response.getWriter();
    try {
        out.print(str);
    }catch (Exception e){
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"loadTrackIdsData");
        System.out.println("Error Case : "+"加载所有的快递单ID"+"失败");
        e.printStackTrace();
    }finally {
        //关闭数据库会话
        transportImpl.closeSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}


//加载快递运输信息
@Override
public void loadData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //获取ajax提交的翻页的num和size
    try {
        this.setPageNum(Integer.parseInt(request.getParameter("page")));
        this.setPageSize(Integer.parseInt(request.getParameter("rows")));
        //测试ajax传入的两个数据是否正确
        //System.out.println("page:"+page+",rows:"+rows);
    }catch (Exception e)
    {
        System.out.println("数据格式转换错误(loadData)!");
    }
    //获取从后台获取的数据
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //获取记录总数
    this.setTotal(transportImpl.sumTransportMsgRecords());
    //将page,rows,total的值传入到chargeManageImpl对象实例
    transportImpl.setTotal(this.getTotal());
    transportImpl.setPage(this.getPageNum());
    transportImpl.setRows(this.getPageSize());
    //获取查询结果
    List list = (List)transportImpl.getTransportMsgRecordsByLimit(new HashMap());
    //打印查询结果
    //使用PrintWriter向ajax传递值
    PrintWriter out = response.getWriter();
    //使用Json工具将取出的数据转化为json数据
    JSONObject jsonObject = null;
    try {
        jsonObject = JsonData.jsonData(list, this.getTotal());
        //向页面发送json格式的数据
        out.print(jsonObject);
    }catch (Exception e){
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"loadData");
        System.out.println("Error Case : "+"加载快递运输信息"+"失败");
        e.printStackTrace();
    }finally {
        //关闭数据库会话
        transportImpl.closeSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

//新增快递运输信息
@Override
public void insertData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //创建一个模型类实例,并给各个属性赋值
    TransportViewModel transportViewModel = new TransportViewModel();
    //获取ajax传递的参数
    String transport_startStation = null;
    Integer track_id = null;
    String transport_nextStation = null;
    if(request.getParameter("transport_startStation") != null && !"".equals(request.getParameter("transport_startStation"))){
        transport_startStation = request.getParameter("transport_startStation");
        transportViewModel.setTransport_startStation(transport_startStation);
    }
    if(request.getParameter("track_id") != null && !"".equals(request.getParameter("track_id"))){
        track_id = Integer.valueOf(request.getParameter("track_id"));
        transportViewModel.setTrack_id(track_id);
    }
    if(request.getParameterValues("transport_nextStation") != null && !"".equals(request.getParameterValues("transport_nextStation"))){
        transport_nextStation = request.getParameter("transport_nextStation");
        transportViewModel.setTransport_nextStation(transport_nextStation);
    }
    //打印参数
    //System.out.println("insert params : "+transportViewModel);
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //调用xxxImpl的方法向数据库插入数据
    int returnValue = 0;
    //执行插入操作
    returnValue = transportImpl.insertTransport(transportViewModel);
    //创建一个输出流对象
    PrintWriter out = response.getWriter();
    //定义一个判断插入是否成功的变量
    boolean flag = false;
    //如果returnValue等于1,表示插入成功,否则失败
    if(returnValue == 1){
        flag = true;
    }
    try {
        out.print(String.valueOf(flag));
    }catch (Exception e){
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"insertData");
        System.out.println("Error Case : "+"新增快递运输信息"+"失败");
        e.printStackTrace();
    }finally {
        //关闭数据库会话
        transportImpl.commitAndCloseSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

//修改快递运输信息
@Override
public void updateData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //创建一个模型类实例,并给各个属性赋值
    TransportViewModel transportViewModel = new TransportViewModel();
    //获取ajax传递的参数
    String transport_startStation = null;
    Integer track_id = null;
    String transport_nextStation = null;
    if(request.getParameter("transport_startStation") != null && !"".equals(request.getParameter("transport_startStation"))){
        transport_startStation = request.getParameter("transport_startStation");
        transportViewModel.setTransport_startStation(transport_startStation);
    }
    if(request.getParameter("track_id") != null && !"".equals(request.getParameter("track_id"))){
        track_id = Integer.valueOf(request.getParameter("track_id"));
        transportViewModel.setTrack_id(track_id);
    }
    if(request.getParameterValues("transport_nextStation") != null && !"".equals(request.getParameterValues("transport_nextStation"))){
        transport_nextStation = request.getParameter("transport_nextStation");
        transportViewModel.setTransport_nextStation(transport_nextStation);
    }
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //调用xxxImpl的方法向数据库插入数据
    int returnValue = transportImpl.updateTransport(transportViewModel);
    //创建一个输出流对象
    PrintWriter out = response.getWriter();
    //定义一个判断插入是否成功的变量
    boolean flag = false;
    //如果returnValue等于1,表示插入成功,否则失败
    if(returnValue == 1){
        flag = true;
    }
    try {
        out.print(String.valueOf(flag));
    }catch (Exception e){
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"updateData");
        System.out.println("Error Case : "+"修改快递运输信息"+"失败");
        e.printStackTrace();
    }finally {
        //关闭数据库会话
        transportImpl.commitAndCloseSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

//删除快递运输信息
@Override
public void deleteData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //获取ajax传递的参数
    Integer transport_id = null;
    if(request.getParameter("transport_id") != null && !"".equals(request.getParameter("transport_id"))){
        transport_id = Integer.valueOf(request.getParameter("transport_id"));
    }
    //查看参数
    //System.out.println("payroll_id : "+payroll_id);
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //调用xxxImpl的方法向数据库插入数据
    int returnValue = transportImpl.deleteTransport(transport_id);
    //创建一个输出流对象
    PrintWriter out = response.getWriter();
    //定义一个判断插入是否成功的变量
    boolean flag = false;
    //如果returnValue等于1,表示插入成功,否则失败
    if(returnValue == 1){
        flag = true;
    }
    try {
        out.print(String.valueOf(flag));
    }catch (Exception e){
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"deleteData");
        System.out.println("Error Case : "+"删除快递运输信息"+"失败");
        e.printStackTrace();
    }finally {
        //关闭数据库会话
        transportImpl.commitAndCloseSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

//查询快递运输信息
@Override
public void searchData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //创建一个Map类实例,并给各个属性赋值
    Map map = new HashMap();
    //获取ajax提交的翻页的num和size
    try {
        this.setPageNum(Integer.parseInt(request.getParameter("page")));
        this.setPageSize(Integer.parseInt(request.getParameter("rows")));
    } catch (Exception e) {
        System.out.println("数据格式转换错误(loadData)!");
    }
    //获取ajax传递的参数
    String transport_startStation = null;
    Integer track_id = null;
    String transport_nextStation = null;
    if(request.getParameter("transport_startStation") != null && !"".equals(request.getParameter("transport_startStation"))){
        transport_startStation = request.getParameter("transport_startStation");
        map.put("transport_startStation",transport_startStation);
    }
    if(request.getParameter("track_id") != null && !"".equals(request.getParameter("track_id"))){
        track_id = Integer.valueOf(request.getParameter("track_id"));
        map.put("track_id",track_id);
    }if(request.getParameter("transport_nextStation") != null && !"".equals(request.getParameter("transport_nextStation"))){
        transport_nextStation = request.getParameter("transport_nextStation");
        map.put("transport_nextStation",transport_nextStation);
    }
    //创建业务操作对象
    TransportImpl transportImpl = new TransportImpl();
    //获取记录总数
    this.setTotal(transportImpl.sumTransportMsgRecords());
    //将page,rows,total的值传入到chargeManageImpl对象实例
    transportImpl.setTotal(this.getTotal());
    transportImpl.setPage(this.getPageNum());
    transportImpl.setRows(this.getPageSize());
    //获取查询结果
    List list = (List) transportImpl.searchTransport(map);
    //打印查询结果
    //使用PrintWriter向ajax传递值
    PrintWriter out = response.getWriter();
    //使用Json工具将取出的数据转化为json数据
    JSONObject jsonObject = null;
    try {
        jsonObject = JsonData.jsonData(list, this.getTotal());
        //向页面发送json格式的数据
        out.print(jsonObject);
    } catch (Exception e) {
        //打印异常信息
        System.out.println("Error Location : "+"TransportServlet"+"."+"searchData");
        System.out.println("Error Case : "+"查询快递运输信息"+"失败");
        e.printStackTrace();
    } finally {
        //关闭数据库会话
        transportImpl.closeSqlSession();
        //刷新输出流
        out.flush();
        //关闭输出流
        out.close();
    }
}

}

操作类:

package com.wzb.impl;

import com.wzb.mappers.LogisticsPathMapper;
import com.wzb.mappers.TransportMapper;
import com.wzb.model.LogisticsPathViewModel;
import com.wzb.model.TransportViewModel;
import com.wzb.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;

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

/**
* Created by Administrator on 2017/5/19 0019.
*/
public class TransportImpl implements TransportMapper {
//封装sqlSession的实例作为成员变量
private SqlSession sqlSession = null;
//封装UserMapper实例作为成员变量
private TransportMapper transportMapper = null;
//封装一个常量保存登录信息表的总数据数量
private Integer total = 0;
//封装翻页的page和rows作为成员变量
//page表示当前的页码
//rows表示当前一页可以存储的记录数
private Integer page = 0;
private Integer rows = 0;

//construvtion method
public TransportImpl() {
    /**
     * 1.在执行方法前实例化sqlSession
     * 2.在执行方法前实例化xxxMapper
     * */
    sqlSession = SqlSessionFactoryUtils.openSession();
    transportMapper = sqlSession.getMapper(TransportMapper.class);
}

/**
 * 该方法用于关闭数据库会话
 */
public void closeSqlSession(){
    sqlSession.close();
}

/**
 * 该方法用于提交数据库的操作和关闭会话
 */
public void commitAndCloseSqlSession(){
    sqlSession.commit();
    sqlSession.close();
}

//setter method and getter method
public Integer getTotal() {
    return total;
}

public void setTotal(Integer total) {
    this.total = total;
}

public Integer getPage() {
    return page;
}

public void setPage(Integer page) {
    this.page = page;
}

public Integer getRows() {
    return rows;
}

public void setRows(Integer rows) {
    this.rows = rows;
}


/**
 * 获取快递运输信息表中的所有记录总数
 * @return
 */
@Override
public int sumTransportMsgRecords() {
    //查询登录信息表一共有多少条信息
    int count =  0;
    try{
        //获取查询的记录总数
        count =  transportMapper.sumTransportMsgRecords();
        //将总数传给total属性
        this.setTotal(count);
    }catch(Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"sumTransportMsgRecords");
        System.out.println("Error Case : "+"获取快递运输信息表中的所有记录总数"+"失败");
        e.printStackTrace();
    }
    return count;
}

/**
 * 根据范围获取对应的快递运输信息表中记录
 * @param map
 * @return
 */
@Override
public List getTransportMsgRecordsByLimit(Map map) {
    //定义可以分得页数
    int pageNum = 0;
    //获取每页存储的数量
    int num = getRows();
    //获取总记录数
    int count = getTotal();
    try {
        //及计算每页显示的数目
        pageNum = (int)Math.ceil((double)count/(double)num);
    }catch (Exception e)
    {
        e.printStackTrace();
    }
    //定义查询的范围的开始编号和结束编号
    int beginIndex = (page - 1) * num;
    int endIndex = 0;
    if(page < pageNum){
        endIndex = page * num - 1;
    }else{
        endIndex = total - beginIndex;
    }
    Map myMap = map;
    myMap.put("beginIndex",beginIndex);
    myMap.put("endIndex",endIndex);
    //查看分页参数
    //System.out.println("分页参数 : "+myMap);
    //获取数据库的查询结果
    List list = (List) transportMapper.getTransportMsgRecordsByLimit(myMap);
    //将集合中的类数据转化为json数据
    List list1 = new ArrayList();
    //定义一个json对象实例保存json数据
    JSONObject jsonObject = null;
    try {
        //将类的每个属性及其对应的数据转化为json键值对
        for(TransportViewModel transportViewModel : list){
            jsonObject = new JSONObject();
            jsonObject.put("transport_id", transportViewModel.getTransport_id());
            jsonObject.put("transport_startStation", transportViewModel.getTransport_startStation());
            jsonObject.put("transport_nextStation", transportViewModel.getTransport_nextStation());
            jsonObject.put("transport_date", transportViewModel.getTransport_date());
            jsonObject.put("track_id", transportViewModel.getTrack_id());
            jsonObject.put("client_id", transportViewModel.getClient_id());
            jsonObject.put("recipients_id", transportViewModel.getRecipients_id());
            jsonObject.put("package_id", transportViewModel.getPackage_id());
            jsonObject.put("employee_id", transportViewModel.getEmployee_id());
            jsonObject.put("track_date", transportViewModel.getTrack_date());
            list1.add(jsonObject);
        }
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"getTransportMsgRecordsByLimit");
        System.out.println("Error Case : "+"根据范围获取对应的快递运输信息表中记录"+"失败");
        e.printStackTrace();
    }
    return list1;
}

/**
 * 获取所有的快递单ID
 * @return
 */
@Override
public List getAllTrackIds() {
    List trackIds = new ArrayList();
    try {
        trackIds = (List)transportMapper.getAllTrackIds();
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"getAllTrackIds");
        System.out.println("Error Case : "+"获取所有的快递单ID"+"失败");
        e.printStackTrace();
    }
    return trackIds;
}

/**
 * trnasport插入数据
 * @param transportViewModel
 * @return
 */
@Override
public int insertTransport(TransportViewModel transportViewModel) {
    int returnValue = 0;
    try {
        returnValue = transportMapper.insertTransport(transportViewModel);
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"insertTransport");
        System.out.println("Error Case : "+"trnasport插入数据"+"失败");
        e.printStackTrace();
    }
    return returnValue;
}

/**
 * trnasport更新数据
 * @param transportViewModel
 * @return
 */
@Override
public int updateTransport(TransportViewModel transportViewModel) {
    int returnValue = 0;
    try {
        returnValue = transportMapper.updateTransport(transportViewModel);
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"updateTransport");
        System.out.println("Error Case : "+"trnasport更新数据"+"失败");
        e.printStackTrace();
    }
    return returnValue;
}

/**
 * trnasport删除数据
 * @param transport_id
 * @return
 */
@Override
public int deleteTransport(int transport_id) {
    int returnValue = 0;
    try {
        returnValue = transportMapper.deleteTransport(transport_id);
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"deleteTransport");
        System.out.println("Error Case : "+"trnasport删除数据"+"失败");
        e.printStackTrace();
    }
    return returnValue;
}

/**
 * trnasport查询数据
 * @param map
 * @return
 */
@Override
public List searchTransport(Map map) {
    //定义可以分得页数
    int pageNum = 0;
    //获取每页存储的数量
    int num = getRows();
    //获取总记录数
    int count = getTotal();
    try {
        //及计算每页显示的数目
        pageNum = (int)Math.ceil((double)count/(double)num);
    }catch (Exception e)
    {
        e.printStackTrace();
    }
    //定义查询的范围的开始编号和结束编号
    int beginIndex = (page - 1) * num;
    int endIndex = 0;
    if(page < pageNum){
        endIndex = page * num - 1;
    }else{
        endIndex = total - beginIndex;
    }
    Map myMap = map;
    myMap.put("beginIndex",beginIndex);
    myMap.put("endIndex",endIndex);
    //查看分页参数
    //System.out.println("分页参数 : "+myMap);
    //获取数据库的查询结果
    List list = (List) transportMapper.searchTransport(myMap);
    //将集合中的类数据转化为json数据
    List list1 = new ArrayList();
    //定义一个json对象实例保存json数据
    JSONObject jsonObject = null;
    try {
        //将类的每个属性及其对应的数据转化为json键值对
        for(TransportViewModel transportViewModel : list){
            jsonObject = new JSONObject();
            jsonObject.put("transport_id", transportViewModel.getTransport_id());
            jsonObject.put("transport_startStation", transportViewModel.getTransport_startStation());
            jsonObject.put("transport_nextStation", transportViewModel.getTransport_nextStation());
            jsonObject.put("transport_date", transportViewModel.getTransport_date());
            jsonObject.put("track_id", transportViewModel.getTrack_id());
            jsonObject.put("client_id", transportViewModel.getClient_id());
            jsonObject.put("recipients_id", transportViewModel.getRecipients_id());
            jsonObject.put("package_id", transportViewModel.getPackage_id());
            jsonObject.put("employee_id", transportViewModel.getEmployee_id());
            jsonObject.put("track_date", transportViewModel.getTrack_date());
            list1.add(jsonObject);
        }
    }catch (Exception e){
        System.out.println("Error Location : "+"TransportImpl"+"."+"searchLogisticPath");
        System.out.println("Error Case : "+"trnasport查询数据"+"失败");
        e.printStackTrace();
    }
    return list1;
}

}

Mapper:

package com.wzb.mappers;

import com.wzb.model.LogisticsPathViewModel;
import com.wzb.model.TransportViewModel;

import java.util.List;
import java.util.Map;

/**
* Created by Administrator on 2017/5/13 0013.
*/
public interface TransportMapper {
//获取快递运输信息表中的所有记录总数
public int sumTransportMsgRecords();
//根据范围获取对应的快递运输信息表中记录
public List

Mapper.xml:

你可能感兴趣的