Currently I have a working application but I would like some advice because I feel like there must be a better solution. One of the features on the site I am building is a feature to show users videos when they search for them. The search would be done by clicking a link like "View All Dreamweaver Tutorials" Each page in the search has a max of 12 videos and if the search has queried more then that you can click a link to go to other pages. Again, all works fine but I am not a fan of my logic and would like to hear if anyone has a better solution to a very common task.
Here’s an example of parameters I might send when the user clicks a link …
search?tag=Dreamweaver&sub=CSS&page=1
Where tag is the main category, sub is the sub category, and page is the current page they would like to see. If the user gives a page that is out of bounds they are directed to a special screen. So if the servlet saw
search?tag=Dreamweaver&sub=CSS&page=1000
It would redirect the user!
Now, here’s a bit of my servlet that grabs these parameters that are sent …
category = request.getParameter("tag");
subCategory = request.getParameter("sub");
page = Integer.parseInt(request.getParameter("page"));
ArrayList<Integer> startStop = Page.getPageStartStop(page);
int start = startStop.get(0);
int stop = startStop.get(1);
videoList = SearchDAO.getSearchResults(category, subCategory, start, stop);
Here is where I do not like my logic. As you can see I first grab the parameters. Fairly normal. But then I call a method in the Page class and send it the page number parameter. So for this example I would be sending the number 1. Then the purpose of that method is to figure out through if statements the start and stop points that the database should query. So that method looks something like this.
public static ArrayList<Integer> getPageStartStop(int page)
{
ArrayList<Integer> startStop = new ArrayList<Integer>();
if (page == 1)
{
startStop.add(0);
startStop.add(12);
return startStop;
}
else if (page == 2)
{
startStop.add(11);
startStop.add(23);
return startStop;
}
......
}
So for the example if page 1 being sent, the method returns 0 for start and 12 for stop and sends those values to my DAO so that the query knows where to start and where to stop. Below is a snippet of my DAO and the last two questions marks become my start and stop.
preparedStatement = connection.prepareStatement("SELECT * FROM videos WHERE category = ? AND subCategory = ? LIMIT ?,?");
So the problem is that Page class needs a lot of if statements to anticipate pages and return their result. Can anyone else think of a better way to do this. Maybe a common algorithm? So many websites utilize this functionality so I know there must be a cleaner way to carry out this problem. It was honestly just the first thing that jumped into my mind. Thank you so much for reading! Comments and answers would be greatly appreciated!
Maybe you can do something like this
And indeed, this is called pagination.