在Struts的FORM中,增加private int pageDisplay = 10; 屬性,並增加對應的setter和getter方法。這個屬性是用來設置每頁顯示的記錄數,10是默認值,可以根據實際情況進行設置。
在Struts的ACTION層,增加一個方法,代碼如下
- package com.excellence.struts.action;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.Action;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import com.excellence.page.Service;
- import com.excellence.struts.form.CheckForm;
- public class CheckAction extends Action {
- public ActionForward execute(
- ActionMapping mapping,
- ActionForm form,
- HttpServletRequest request,
- HttpServletResponse response) {
- setSubPage(request,form);
- return mapping.findForward("result");
- }
- private void setSubPage(HttpServletRequest request,ActionForm form){
- CheckForm thisForm = (CheckForm)form;
- String content = thisForm.getContent();//查詢條件中的內容
- Service service = new Service();
- //拿到每頁要顯示的記錄數
- int pageSize = thisForm.getPageDisplay();
- request.setAttribute("pageSize",pageSize+"");
- //拿到目前要顯示得頁數
- int pageNumber = 1;
- String strPageNumber = request.getParameter("page");
- if(strPageNumber != null)
- pageNumber = Integer.parseInt(strPageNumber);
- //計算要顯示的頁數得第一條記錄的位置
- int start = 0;
- start = (pageNumber - 1)*pageSize;
- List result = service.findByCondition("from Subpage where content like ? order by content",new Object[]{content},start,pageSize);
- List counts = service.findByCondition("select count(*) from Subpage where content like ?",new Object[]{content});
- int count = Integer.parseInt(counts.get(0).toString());
- request.setAttribute("count",count+"");//總條數
- // 設置總頁數
- int totalPage = count % pageSize == 0 ? count / pageSize : (count / pageSize + 1);
- request.setAttribute("totalPage",totalPage+"");
- request.setAttribute("result",result);
- if(result.size() == 0)
- request.setAttribute("result",null);
- }
- }