今天讲的主题是在Java中如何利用bsgrid插件进行分页查询,让查询变得更简单、代码更加通俗易懂、程序运行效率更高。
<body style="text-align:center">
<div class="center_text">
<table id="userTable">
<tr>
<th w_index="id" w_hidden="true">id</th>
<th w_index="name">姓名</th>
<th w_index="sex">性别</th>
<th w_index="age">年龄</th>
<th w_index="phone">手机号</th>
<th w_index="address">地址</th>
<th w_index="roleName">用户组</th>
<th w_render="optionSet">操作</th>
</tr>
</table>
</div>
//引用到的插件
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery.bsgrid-1.37/merged/grid.all.min.css">
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery.bsgrid-1.37/css/skins/grid_gray.min.css">
<script type="text/javascript" src="${ctx}/js/jquery-1.12.4/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery.bsgrid-1.37/js/lang/grid.zh-CN.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery.bsgrid-1.37/merged/grid.all.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
//初始化 bsgrid tableSkinDetails
tableSkinDetails = $.fn.bsgrid.init('userTable', {
url: "${ctx}/servlet/UserServlet?fun=bsGridList",
autoLoad: true,
stripeRows: true,//隔行变色
rowHoverColor: true,//划过行变色
pageSize: 10,
ageAll: false,
pageSizeSelect: true,//是否选择分页页数下拉框
pagingLittleToolbar: true,//精简的图标按钮分页工具条
pagingToolbarAlign: "left",//分页工具条的显示位置
displayBlankRows: false,//不显示空白行
});
});
//自定义事件
function optionSet(record, rowIndex, colIndex, options){
//record这个参数就包含了这条数据的所有
var id =record.id;
//返回自定义内容
return '<a href="${ctx}/servlet/UserServlet?fun=toUpdate&id='+id+'">修改</a>'+
'<a href="${ctx}/servlet/UserServlet?fun=delete&id='+id+'">删除</a>';
}
</script>
</body>
对判断的情况,封装一个类
public class Tools{
public static boolean isNotNull(String value){
if(value==null || "".equals(value.trim())|| "null".equalsIgnoreCase(value) ) {
return false;
}
return true;
}
//转换为utf-8编码
public static String ISOtoUTF8(String s) {
try { s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (Exception e) {
}
return s;
}
public static boolean isNum(String str){
return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
}
}
对bsgrid的一些返回值进行封装,这个一般放在vo包里面
public class Bsgrid<T> {
private boolean success;
private int totalRows;
private int curPage;
private List<T> data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
Servlet代码如下:
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//bsgrid查询的方法的调用
String currentPageStr=request.getParameter("curPage");
String pageSizeStr=request.getParameter("pageSize");
//设置当前页和当前页的大小
int currentPage=1;
int pageSize=10;
//调用声明那类的方法进行判断值
if (currentPageStr!=null && Tools.isNum(currentPageStr)) {
currentPage=Integer.parseInt(currentPageStr);
}
if (pageSizeStr!=null &&Tools.isNum(pageSizeStr)) {
pageSize=Integer.parseInt(pageSizeStr);
}
//开始取值的值
int startIndex=(currentPage-1)*pageSize;
IUserService userService = new UserSerivceImpl();
//调用分页查询的方法
List<UserPo> listUser = userService.findAll(startIndex,pageSize);
int totalRow=userService.getTotalRow();
//实例化bsgrid插件
Bsgrid<UserPo> bsgrid=new Bsgrid<UserPo>();
bsgrid.setSuccess(true);
bsgrid.setCurPage(currentPage);
bsgrid.setTotalRows(totalRow);
bsgrid.setData(listUser);
//用json进行数据返回
JSONObject jsonObject=JSONObject.fromObject(bsgrid);
PrintWriter out=response.getWriter();
out.write(jsonObject.toString());
//关闭流
out.flush();
out.close();
}
}
再创建一个dao的实现类
public class UserDaoImpl implements IUserDao {
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
//查询的sql语句
private String findAllPage = "SELECT user.*,role.roleName FROM role INNER JOIN USER ON user.rid = role.id limit ?,?";
private String getTotalRow="SELECT COUNT(*) FROM user";
public List<UserPo> findAll(int startIndex, int pageSize) {
List<UserPo> list = new ArrayList<UserPo>();
UserPo user = null;
try {
conn = DbUtil.getConnection();
ps = conn.prepareStatement(findAllPage);
ps.setInt(1, startIndex);
ps.setInt(2, pageSize);
rs = ps.executeQuery();
list=JdbcHelper.getResult(rs, UserPo.class);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtil.close(conn, ps, rs);
}
return list;
}
public int getTotalRow() {
int intTotalRow=0;
try {
conn=DbUtil.getConnection();
ps=conn.prepareStatement(getTotalRow);
rs=ps.executeQuery();
while (rs.next()) {
intTotalRow=rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
DbUtil.close(conn, ps, rs);
}
return intTotalRow;
}
}