Monday, March 16, 2009

Creating google wannabe paging

As my several notes that copied to my blog, I will write a note again and then Ill copy to blog again although its a java theme, in case I think there are reader from facebook rather than from blogspot. And especially my blog is already long time don't have a java post.

Yesterday in milist Java User Group-Indonesia, there is a member asked about how to create paging list in java-application. I face the same problem in my first project in balicamp. I cannot find component that fetch query with limitation. Displaytag component select all records and then view it page by page as user needed. While valulist donot use hibernate, data framework that shoud be standard as java application. I will make the select in other post, but now I want to show you ho to make google paging mine version.

If you were googling, there will be list of paging if the result is a lot, such as: Previous 1 2 3 4 5 6 7 8 9 10 Next. It's easy not as scared as we saw it in google. it's only playing with some if and else in jsp with some of parameters.

Im a spring guy, spring is one kind of a framework that needed in building java application, and it playing class called controller, in easy word, we have a controller for each page we make. we need 3 parameters (information) for a controller for our paging:
1. page, the page that user request, for example is 5
2. totalPages, total of the pages, get from select count / perPage, which is perPage is total record every page.
for example total record = 100, perPage 10 record, so totalPages = 10
3. listPages, list pages that shown.
for example we viewing 5 pages, ther listPages is 3 4 5 6 7,

Meanwhile in the jsp the algorithm such as below:
1. if page != 1 then print First, anchor to page=1
2. print every value of listPages, if equals with the requested page, then no anchor needed, otherwise anchor to the page
3. if totalPage != 0 and requested page != total
3. jika totalPage != 0 dan page yg direquest != totalPages then print Last, anchor to the last page.
the result for our example is First 3 4 5 6 7 Last.

write all of that step into separated jsp file, we only need to include as we need it, we put it above our table.

As compare with google, google used 20 list of pages if the record is a lot. we already have the similar with google, unless if also set listPages size 20 same as google, and the page is 5 for example we print 20 pages from 1 to 20, while google only print 10 page. As far the page is below 10 google show only 10 page.

The other different is google print Previous and Next, while mine prints First and Last, and FYI, I prefer mine ^_^, I think it also applicable for other than java, because it's an algorithm not language-based, thank you for reading & have a nice try!!

No comments: