从头开始基于Maven搭建SpringMVC+Mybatis项目(3)
接上文内容,本节介绍基于Mybatis的查询和分页功能,并展示一个自定义的分页标签,可重复使用以简化JSP页面的开发。
在上一节中,我们已经使用Maven搭建好了项目的基础结构,包括一个父项目petstore-parent和数据库持久层模块petstore-persist及Web站点petstore-web,现在来为petstore-web添加一些功能。对于初学者来说,可能第一个遇到的较复杂问题就是分页查询,那么就先从解决它开始。
看一下完成的效果:
上面是四个可选的查询条件,用户可以根据需要组合查询条件。
中间是符合条件的数据展示表格,对查询结果可以执行修改和删除操作,但是暂未实现。
最下面是一个分页导航栏,以自定义标签(Tag)技术实现,可复用到多个jsp页面。
下面来介绍关键步骤和代码。首先是petstore-persist模块,目录结构如下:
Product.Java是一个普通的JavaBean,这里略过。ProductMapper.java中定义了两个方法:
- package com.example.petstore.persist.model;
- import java.util.List;
- import org.apache.ibatis.annotations.Param;
- public interface ProductMapper {
- /**
- * 查询符合条件的记录总数
- * @param id
- * @param name
- * @param fromPrice
- * @param toPrice
- * @return
- */
- int matches(@Param(value="id") int id, @Param(value="name") String name, @Param(value="fromPrice") float fromPrice, @Param(value="toPrice") float toPrice);
- /**
- * 按查询条件及分页条件分段查询记录
- * @param id
- * @param name
- * @param fromPrice
- * @param toPrice
- * @param fetchIndex
- * @param fetchCount
- * @return
- */
- List<Product> findProducts(@Param(value="id") int id, @Param(value="name") String name, @Param(value="fromPrice") float fromPrice, @Param(value="toPrice") float toPrice, @Param(value="fetchIndex") int fetchIndex, @Param(value="fetchCount") int fetchCount);
- }
使用时,首先调用matches方法获得符合条件的记录总数,然后根据每页显示的记录数和当前页数计算读取数据的Limit偏移量和记录数,再调用findProducts方法读取数据。两个方法的参数都使用了@Param注解,例如@Param(value="id") int id,在映射文件中,可通过#{id}的格式来使用这个参数。
在Product.xml中添加两个方法的SQL映射:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.example.petstore.persist.model.ProductMapper">
- <resultMap type="com.example.petstore.persist.model.Product"
- id="productMap">
- <id column="p_id" property="id" />
- <result column="p_name" property="name" />
- <result column="p_price" property="price" />
- </resultMap>
- <select id="matches" resultType="int">
- select count(*) from t_product
- <where>
- <if test="id>0">
- p_id=#{id}
- </if>
- <if test="name!=null and name!='' ">
- and locate(#{name},p_name)>0
- </if>
- <if test="fromPrice>-1">
- and p_price>=#{fromPrice}
- </if>
- <if test="toPrice>-1">
- and p_price<=#{toPrice}
- </if>
- </where>
- </select>
- <select id="findProducts" resultMap="productMap">
- select * from t_product
- <where>
- <if test="id>0">
- p_id=#{id}
- </if>
- <if test="name!=null and name!='' ">
- and locate(#{name},p_name)>0
- </if>
- <if test="fromPrice>-1">
- and p_price>=#{fromPrice}
- </if>
- <if test="toPrice>-1">
- and p_price<=#{toPrice}
- </if>
- </where>
- limit #{fetchIndex},#{fetchCount}
- </select>
- </mapper>
可以看到上面两个方法中,就是通过<where><if>等元素来组装查询SQL。Mybatis的优点之一就是直接使用SQL语法,有SQL基础的情况下非常容易上手。
下面进入petstore-web模块,先来看整体结构:
其中com.example.petstore.web.tag.PagingTag.java是分页标签类,关键代码:
- private int pageIndex = 1; //当前页数
- private int pageSize = 20; //默认每页行数
- private int pageCount = 0; //记录总页数
- private int itemCount = 0; //记录总条数
- private int numCount = 10; //分页栏数字导航链接个数
- @Override
- public void doTag() throws JspException, IOException {
- JspWriter out = this.getJspContext().getOut();
- out.write("<script type=\"text/javascript\">function navigatorPage(pageIndex) {document.getElementById('pageIndex').value = pageIndex;document.forms[0].submit();}</script>");
- out.write("每页显示");
- out.write("<select id='pageSize' name='pageSize' onchange='navigatorPage(" + pageIndex + ")'>");
- out.write("<option value='5'" + (pageSize == 5 ? " selected='true'" : "") + ">5</option>");
- out.write("<option value='10'" + (pageSize == 10 ? " selected='true'" : "") + ">10</option>");
- out.write("<option value='20'" + (pageSize == 20 ? " selected='true'" : "") + ">20</option>");
- out.write("<option value='50'" + (pageSize == 50 ? " selected='true'" : "") + ">50</option>");
- out.write("<option value='100'" + (pageSize == 100 ? " selected='true'" : "") + ">100</option>");
- out.write("<option value='500'" + (pageSize == 500 ? " selected='true'" : "") + ">500</option>");
- out.write("</select>");
- out.write("条 ");
- out.write(pageIndex + "/" + pageCount + "页 ");
- out.write("共" + itemCount + "条记录 ");
- out.write("<input type='button' value='第一页' onclick='javascript:navigatorPage(1);'" + (pageIndex > 1 ? "" : " disabled='true'") + " /> ");
- out.write("<input type='button' value='上一页' onclick='javascript:navigatorPage(" + (pageIndex - 1) + ");'" + (pageIndex > 1 ? "" : " disabled='true'") + " /> ");
- //数字导航栏
- int iStartIndex = 1;
- int iEndIndex = pageCount;
- if(pageCount <= numCount) {
- } else if ((pageIndex + (numCount + 1) / 2) > pageCount) {
- iStartIndex = pageCount - (numCount - 1);
- iEndIndex = pageCount;
- } else if (pageIndex <= (numCount + 1) / 2) {
- iEndIndex = numCount;
- } else {
- if (numCount % 2 == 0) {
- iStartIndex = pageIndex - numCount / 2;
- iEndIndex = pageIndex + (numCount - 1) / 2;
- } else {
- iStartIndex = pageIndex - numCount / 2;
- iEndIndex = pageIndex + numCount / 2;
- }
- }
- for(int i = iStartIndex; i <= iEndIndex; i++) {
- if(i == pageIndex) {
- out.write("<strong>" + i + "</strong> ");
- } else {
- out.write("<a href='javascript:navigatorPage(" + i + ");'>" + i + "</a> ");
- }
- }
- out.write("<input type='button' value='下一页' onclick='javascript:navigatorPage(" + (pageIndex + 1) + ");'" + (pageIndex < pageCount ? "" : " disabled='true'") + " /> ");
- out.write("<input type='button' value='最后页' onclick='javascript:navigatorPage(" + pageCount + ");'" + (pageIndex < pageCount ? "" : " disabled='true'") + " />");
- out.write("<input type='hidden' id='pageIndex' name='pageIndex' value='" + pageIndex + "'/>");
- }
接下来还需要一个标签配置文件来声明这个标签的使用方法。
在WEB-INF下建立目录tld,然后添加pagingTag.tld,内容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE taglib
- PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
- "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
- <taglib>
- <tlib-version>2.0</tlib-version>
- <jsp-version>1.2</jsp-version>
- <short-name>Paging</short-name>
- <uri>http://blog.csdn.net/autfish/tag/</uri>
- <display-name>Paging Tag</display-name>
- <description>Paging Tag library</description>
- <tag>
- <name>pagingTag</name>
- <tag-class>com.example.petstore.web.tag.PagingTag</tag-class>
- <body-content>empty</body-content>
- <description>create navigation for paging</description>
- <attribute>
- <name>pageIndex</name>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>pageSize</name>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>pageCount</name>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>itemCount</name>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- </tag>
- </taglib>
注意其中的uri元素,这里并不需要配置真实存在的url,但该uri在你的classpath中应保持唯一,不能被其他组件声明使用。
在web.xml中启用这个标签:
- <jsp-config>
- <taglib>
- <taglib-uri>http://blog.csdn.net/autfish/tag/</taglib-uri>
- <taglib-location>/WEB-INF/tld/pagingTag.tld</taglib-location>
- </taglib>
- </jsp-config>
在jsp中使用:
- <%@ taglib prefix="my" uri="http://blog.csdn.net/autfish/tag/" %>
- <my:pagingTag pageIndex="${contentModel.pageIndex}" pageSize="${contentModel.pageSize}" pageCount="${contentModel.pageCount}" itemCount="${contentModel.itemCount}" />
对于四个属性的赋值,contentModel是一个PagingList.java类的实例,用于辅助分页,由分页属性和数据表构成,在Controller中填充数据并传递到视图JSP。属性如下:
- private int pageIndex = 1;
- private int pageSize = 20;
- private int pageCount = 0;
- private int itemCount = 0;
- private List<T> items;
Controller代码:
- @Controller
- @RequestMapping("/product")
- public class ProductController {
- @Autowired
- private ProductService productService;
- @RequestMapping(value="/list")
- public String listProduct(Model model, @ModelAttribute("searchModel") SearchModel formModel,
- @RequestParam(value=PagingList.PAGE_INDEX_NAME, defaultValue="1") int pageIndex,
- @RequestParam(value=PagingList.PAGE_SIZE_NAME, defaultValue="10") int pageSize) {
- int id = 0;
- String name = "";
- float fromPrice = -1;
- float toPrice = -1;
- if(formModel != null) {
- id = NumberUtils.toInt(formModel.getId(), 0);
- name = formModel.getName();
- fromPrice = NumberUtils.toFloat(formModel.getFromPrice(), -1);
- toPrice = NumberUtils.toFloat(formModel.getToPrice(), -1);
- }
- model.addAttribute("searchModel", formModel);
- PagingList<Product> contentModel = this.productService.findProducts(id, name, fromPrice, toPrice, pageIndex, pageSize);
- model.addAttribute("contentModel", contentModel);
- return "product/list";
- }
- }
Controller中注入了一个ProductService的实例,用于管理持久层的调用,主要代码如下:
- @Service
- public class ProductServiceStdImpl implements ProductService {
- @Autowired
- private ProductMapper productMapper;
- @Override
- public PagingList<Product> findProducts(int id, String name,
- float fromPrice, float toPrice, int pageIndex, int pageSize) {
- int total = this.productMapper.matches(id, name, fromPrice, toPrice);
- int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
- if(pageIndex > pageCount)
- pageIndex = pageCount;
- int fetchIndex = (pageIndex - 1) * pageSize;
- int fetchCount = fetchIndex + pageSize > total ? (total - fetchIndex) : pageSize;
- List<Product> list = this.productMapper.findProducts(id, name, fromPrice, toPrice, fetchIndex, fetchCount);
- PagingList<Product> paging = new PagingList<Product>();
- paging.setItemCount(total);
- paging.setPageCount(pageCount);
- paging.setPageIndex(pageIndex);
- paging.setPageSize(pageSize);
- paging.setItems(list);
- return paging;
- }
- }
限于篇幅,不能把所有的源码一一粘贴,有兴趣可以下载源码。
在WEB容器如tomcat中运行petstore-web模块,使用http://localhost:8080/petstore-web/product/list访问,顺利的话就看到了一开始的画面。如果出错,比对源码检查差异即可。
总结
分页查询功能使用频繁,且开发比较复杂,按需定制一套可复用的分页组件对提高开发效率有很大的帮助。下一节我们继续完善Web模块,增加增删改查以及权限控制功能。
从头开始基于Maven搭建SpringMVC+Mybatis项目(3)的更多相关文章
- 从头开始基于Maven搭建SpringMVC+Mybatis项目(1)
技术发展日新月异,许多曾经拥有霸主地位的流行技术短短几年间已被新兴技术所取代. 在Java的世界中,框架之争可能比语言本身的改变更让人关注.近几年,SpringMVC凭借简单轻便.开发效率高.与spr ...
- 从头开始基于Maven搭建SpringMVC+Mybatis项目(2)
接上文内容,本节介绍Maven的聚合和继承. 从头阅读传送门 互联网时代,软件正在变得越来越复杂,开发人员通常会对软件划分模块,以获得清晰的设计.良好的分工及更高的可重用性.Maven的聚合特性能把多 ...
- 从头开始基于Maven搭建SpringMVC+Mybatis项目(4)
接上文内容,上一节中的示例中完成了支持分页的商品列表查询功能,不过我们的目标是打造一个商品管理后台,本节中还需要补充添加.修改.删除商品的功能,这些功能依靠Mybatis操作数据库,并通过Spring ...
- maven搭建springmvc+mybatis项目
上一篇中已经成功使用maven搭建了一个web项目,本篇描述在此基础上怎么搭建一个基于springmvc+mybatis环境的项目. 说了这么久,为什么那么多人都喜欢用maven搭建项目?我们都知道m ...
- Maven搭建SpringMVC+Mybatis项目详解
前言 最近比较闲,复习搭建一下项目,这次主要使用spring+SpringMVC+Mybatis.项目持久层使用Mybatis3,控制层使用SpringMVC4.1,使用Spring4.1管理控制器, ...
- Maven搭建SpringMVC+MyBatis+Json项目(多模块项目)
一.开发环境 Eclipse:eclipse-jee-luna-SR1a-win32; JDK:jdk-8u121-windows-i586.exe; MySql:MySQL Server 5.5; ...
- Maven搭建SpringMVC+Hibernate项目详解 【转】
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
- Maven搭建SpringMVC + SpringJDBC项目详解
前言 上一次复习搭建了SpringMVC+Mybatis,这次搭建一下SpringMVC,采用的是SpringJDBC,没有采用任何其他的ORM框架,SpringMVC提供了一整套的WEB框架,所以如 ...
- Maven搭建SpringMVC+Hibernate项目详解
前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这 ...
随机推荐
- ESL翻译:Linear Methods for Regression
chapter 3: Linear Methods for Regression 第3章:回归的线性方法 3.1 Introduction A linear regression model assu ...
- Flink升级到1.4版本遇到的坑
Flink 1.4没出来以前,一直使用Flink 1.3.2,感觉还算稳定,最近将运行环境升级到1.4,遇到了一些坑: 1.需要将可运行程序,基于1.4.0重新编译一次 2.对比了一下flink-co ...
- Python学习日记:day2
1.格式化输出 name = input("请输入你的名字:") age =input("请输入你的年龄:") job =input("请输入你的工作 ...
- lua 批量重命名文件
local s = io.popen("dir F:\\headicon /b/s") local filelist = s:read("*all") loca ...
- Redis分布式集群搭建
Redis集群架构图 上图蓝色为redis集群的节点. 节点之间通过ping命令来测试连接是否正常,节点之间没有主区分,连接到任何一个节点进行操作时,都可能会转发到其他节点. 1.Redis的容错机制 ...
- centOS7 jdk安装
1.查找需要卸载的OpenJDK: # rpm -qa | grep java 2:依次卸载 rpm -e --nodeps javapackages-tools-3.4.1-6.el7_0.noa ...
- sql经典试题
1.一道SQL语句面试题,关于group by表内容:2005-05-09 胜2005-05-09 胜2005-05-09 负2005-05-09 负2005-05-10 胜2005-05-10 负2 ...
- Visual Studio 我的插件
为了以后开发方便,自己记录下好用的Visual Studio 扩展 1.outline if折叠 2.Indent Guides 代码块虚线 3.CodeMaid 大文件里能够重构文件,快速定位方法. ...
- Apache Avro# 1.8.2 Specification (Avro 1.8.2规范)一
h4 { text-indent: 0.71cm; margin-top: 0.49cm; margin-bottom: 0.51cm; direction: ltr; color: #000000; ...
- 联想笔记本电脑 Z500除尘过程
首先说明联想z500真的是特别难拆,主要是C面的键盘如果没有垫片的话很难拆下,建议准备好垫片再进行. 第一步 首先拆掉背面的五个螺丝钉,然后打开四个垫子注意方向,把隐藏的另外四个螺丝拆掉. 第二步 把 ...