发表于: 2018-03-31 22:48:47
1 502
今天完成的事情:
ssm实现分页
这里有两种方法一种是手动sql实现分页,还有一种是用mybatis分页插件PageHelper。
第一种:手动sql
添加一个分页类
public class Page {
private int start=0;
private int count=5;
private int last=0;
public void calculateLast(int total) {
if ((total % count) == 0) {
last=total-count;
}else {
last=total-total%count;
}
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getLast() {
return last;
}
public void setLast(int last) {
this.last = last;
}
}
在CategoryMapper.xml中修改list,根据当有分页信息的时候,进行分页查询
增加total sql语句
<select id="list" resultType="Category">
select * from category_
<if test="start!=null and count!=null">
limit #{start},#{count}
</if>
</select>
<select id="total" resultType="int">
select count(*) from category_
</select>
然后再dao接口中增加对应的方法
控制器中
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page) {
ModelAndView mav = new ModelAndView();
List<Category> cs= categoryService.list();
int total = categoryService.total();
page.calculateLast(total);
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
}
然后jsp页面是
但是这样写就会有两个bug
在首页的时候由于start=0,
然后点击上一页的时候start=start-count=-5,接着就会出现
同样的在末页的时候start=100
然后又在网上看到可以这样改,
其中<a href="javascript:void(0)">的意思就是你点击了这个上一页或下一页也没有变化。
第二种方法是:利用PageHelper插件
在applicationContext.xml中添加插件
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.ssm.model" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/ssm/dao/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value></value>
</property>
</bean>
</array>
</property>
</bean>
当然也可以单独建一个mybatis配置文件在加载进来。
然后在CategoryMapper.xml中去掉limit语句,只留一个普通查询就好
CategoryController在调用categoryService.list(); 之前,执行
PageHelper.offsetPage(page.getStart(),5);
并通过int total = (int) new PageInfo<>(cs).getTotal();获取总数。
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(Page page) {
ModelAndView mav = new ModelAndView();
PageHelper.offsetPage(page.getStart(),5);
List<Category> cs= categoryService.list();
int total = (int) new PageInfo<>(cs).getTotal();
page.calculateLast(total);
// 放入转发参数
mav.addObject("cs", cs);
// 放入jsp路径
mav.setViewName("listCategory");
return mav;
}
}
运行结果正常,并且在首页和末页也没有出现跳转的问题,可以正常跳转。
明天计划的事情:
实现分页+crud
遇到的问题:
关于mybatis的分页插件PageHelper还不知道怎么运用,看到有PageInfo和PageHelper,明天可能还要研究研究。
收获:
实现了分页,知道可以通过sql语句来分页和使用插件来分页。
进度:任务二步骤二
任务开始时间:3.23
预计demo时间:4.3
是否延期:否
禅道地址:http://task.ptteng.com/zentao/project-task-562.html
评论