Sunday, March 15, 2009

AJAX Paging Internals

PagingCalc java class described in Paging Internals could be used in usual and AJAX web applications.

This AJAX Paging Demo web project is based on MVC model 1.
Specifications: Servlet 2.5. Libraries: json-lib-2.2.3.
It could be tested with Tomcat 6.0.x and it could be built with Maven 2.

Check the code below:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);

PagingBean bean = getPagingBean(request);
JSONObject jsonObject = JSONObject.fromObject(bean);

response.setHeader("Content-type", "text/json");
response.getOutputStream().print(jsonObject.toString());
}

private PagingBean getPagingBean(HttpServletRequest request){
int currPage = getCurrPage(request);

PagingCalc calc = new PagingCalc(PagingCalc.DEFAULT_ITEMS_COUNT,
PagingCalc.DEFAULT_INDEXES_COUNT, currPage, dataIF.getDataRowsCount());

PagingBean bean = new PagingBean();
bean.setData(dataIF.getDataRows(calc.getStartItem(), calc.getEndItem()));
bean.setActionUrl("json");
bean.setCurrPageParam(PagingBean.DEFAULT_CURR_PAGE_PARAM);
bean.setCalc(calc);

return bean;
}

Servlet returns JSON like next:
{"actionUrl":"json",
"calc":{"currPage":2,
"endItem":6,
"endPage":5,
"firstLink":1,
"firstLinkVisible":true,
"lastLink":8,
"lastLinkVisible":true,
"nextLink":6,
"nextLinkVisible":true,
"pagesCount":8,
"prevLink":0,
"prevLinkVisible":false,
"startItem":4,
"startPage":1,
"totalItems":23},
"currPageParam":"currPage",
"data":[{"description":"description 4","id":"4","name":"name 4"},
{"description":"description 5","id":"5","name":"name 5"},
{"description":"description 6","id":"6","name":"name 6"}]}

Download project binary and sources.

No comments: