在 Service 层中,调用 getPageData 方法即可:可以将分页方法写在工具类中,让其返回一个包含分页数据的 List 对象。在 Service 层和 DAO 层中,直接调用该方法即可。
下面是 Page 类:
public class Page<T> {
private int start; // 当前位置
private int count; // 每页显示的数据数量
private int total; // 数据总个数
// 默认每页显示5条数据
private static final int DEFAULT_COUNT = 5;
public Page() {
this(DEFAULT_COUNT, 0);
}
public Page(int count, int start) {
this.count = count;
this.start = start;
}
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 getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public boolean isHasPrevious() {
return start > 0;
}
public boolean isHasNext() {
return start + count < total;
}
public int getTotalPage() {
if (total == 0) {
return 1;
}
if (total % count == 0) {
return total / count;
} else {
return total / count + 1;
}
}
public int getLast() {
return total - total % count;
}
public List<T> getPageData(List<T> list) {
if (list == null || list.isEmpty()) {
return new ArrayList<>();
}
int size = list.size();
int end = start + count;
if (end > size) {
end = size;
}
return list.subList(start, end);
}
@Override
public String toString() {
return "Page [start=" + start + ", count=" + count + ", total=" + total + ", getStart()=" + getStart()
+ ", getCount()=" + getCount() + ", isHasPrevious()=" + isHasPrevious() + ", isHasNext()="
+ isHasNext() + ", getTotalPage()=" + getTotalPage() + ", getLast()=" + getLast() + "]";
}
}
在 Service 层中,调用 getPageData 方法即可:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findUsersByPage(int page, int pageSize) {
Page<User> pager = new Page<>(pageSize, (page - 1) * pageSize);
List<User> userList = userDao.listAll();
pager.setTotal(userList.size());
return pager.getPageData(userList);
}
}
在Dao层
@Override
public List<User> listAll() {
return userDatabase;
}
在 Controller 层中,则直接调用 Service 层的方法即可:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/users")
public ModelAndView users(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int pageSize) {
ModelAndView modelAndView = new ModelAndView("users");
List<User> userList = userService.findUsersByPage(page, pageSize);
modelAndView.addObject("userList", userList);
return modelAndView;
}
}
这样的话,就可以在工具类中实现分页逻辑,并且让 Service 层和 DAO 层直接调用。这样就可以减少代码重复,提高代码的复用性
1518

被折叠的 条评论
为什么被折叠?



