One of the very many reasons that scriptlets were obsoleted and discredited over 12 years ago was just this very type of problem. Java code should be in a Java class and never in a JSP.
Also, even supposing all that was in a Java class, there is still a problem. The query is being done each time so it doesn't make sense to talk about going to the first/last part. It would make sense to have a button control the sorting or paging of the result. Which would be passed to the query to change/limit the results.
This is the sort of thing that DataTables was made for. And Bear and Jeanne are offering you critical advice; pay heed. You are headed down a long, ugly road with the style of coding that you are using. Your jsp should end up looking something like this:
This is just an example from one of my pages; it's not meant to address your question directly. But notice that there are no scriplets and no database functions in the page. All that belongs at another layer. A servlet calls a DAO which manages the database functions. Jquery, AJAX and DataTables build the page components and insert them when and where needed. A different servlet handles exporting to Excel.
"The good news about computers is that they do what you tell them to do. The bad news is that they do what you tell them to do." -- Ted Nelson