Hello Everyone,
I am trying to achieve pagination using jsp javascript and servlets.
Here is my code below:
SearchUserViews.java
`package TestPackage;
/**
*
* @author Sagar
*/
private String _userid;
private String _firstName;
private String _lastName;
private String _emailAddress;
public userProfile(){
_userid = "";
_firstName = "";
_lastName = "";
_emailAddress = "";
}
public String getUserid() {
return _userid;
}
public void setUserid(String userid) {
this._userid = userid;
}
public String getFirstName() {
return _firstName;
}
public void setFirstName(String firstName) {
this._firstName = firstName;
}
public String getLastName() {
return _lastName;
}
public void setLastName(String lastName) {
this._lastName = lastName;
}
public String getEmailAddress() {
return _emailAddress;
}
public void setEmailAddress(String emailAddress) {
this._emailAddress = emailAddress;
}
}
navigateDataGrid.java
package TestPackage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class navigateDatagrid extends HttpServlet
{
public static void clearCookieUserManager(HttpServletRequest request, HttpServletResponse response) {
Cookie[] collectionCookies = request.getCookies();
for (Cookie c : collectionCookies) {
if (c.getName().equalsIgnoreCase("FirstTimeAccessUserManager")) {
c.setValue("");
response.addCookie(c);
break;
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
String buttonAction = request.getParameter("action");
HttpSession session = request.getSession(false);
int limitStart = 0;
int limitMax = 10;
int pageSize = 10;
int allUserCount = 0;
int pageIndex = 0; //start page from index 0
session = request.getSession(false);
if (session.getAttribute("limitStart") != null) {
limitStart = Integer.parseInt(session.getAttribute("limitStart").toString());
} else {
session.setAttribute("limitStart", limitStart);
}
if (session.getAttribute("limitMax") != null) {
limitMax = Integer.parseInt(session.getAttribute("limitMax").toString());
} else {
session.setAttribute("limitMax", limitMax);
}
if (session.getAttribute("pageIndex") != null) {
pageIndex = Integer.parseInt(session.getAttribute("pageIndex").toString());
} else {
session.setAttribute("pageIndex", pageIndex);
}
if (session.getAttribute("pageSize") != null) {
pageSize = Integer.parseInt(session.getAttribute("pageSize").toString());
} else {
session.setAttribute("pageSize", pageSize);
}
if (buttonAction.equalsIgnoreCase("Next")) {
limitStart += pageSize;
limitMax = pageSize;//max row return from query
pageIndex += 1;
}else if(buttonAction.equalsIgnoreCase("Previous")){
limitStart -= pageSize;
limitMax = pageSize;//max row return from query
pageIndex -= 1;
}else{
//reset all value to default
limitStart = 0;
limitMax = 0;//max row return from query
pageSize = Integer.parseInt(buttonAction);
pageIndex = 0;
}
session.setAttribute("limitMax", limitMax);
session.setAttribute("pageIndex", pageIndex);
session.setAttribute("limitStart", limitStart);
session.setAttribute("pageSize", pageSize);
response.sendRedirect(request.getContextPath() + "/DataGrid.jsp");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
userServices.java
package TestPackage;
/**
*
* @author Sagar
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
public class userServices {
public Connection getDbConn() {
if(_dbConn == null){
_dbConn = CheckConnection();
}
return _dbConn;
}
public void setDbConn(Connection aDbConn) {
_dbConn = aDbConn;
}
public static String getDbUrl() {
return _dbUrl;
}
public static void setDbUrl(String aDbUrl) {
_dbUrl = aDbUrl;
}
public static String getUser() {
return _user;
}
public static void setUser(String aUser) {
_user = aUser;
}
public static String getDbPassword() {
return _dbPassword;
}
public static void setDbPassword(String aDbPassword) {
_dbPassword = aDbPassword;
}
private List<userProfile> _collectionOfUserProfile;
private static Connection _dbConn;
private static String _dbUrl = "jdbc:oracle:thin:@localhost:1521:QUIZLIVE";
private static String _user = "contestant";
private static String _dbPassword = "Sagar_007";
private final static Logger LOGGER = Logger.getLogger(userServices.class.getName());
public userServices() {
_collectionOfUserProfile = new ArrayList<>();
_dbUrl = "jdbc:oracle:thin:@localhost:1521:QUIZLIVE";
_user = "contestant";
_dbPassword = "Sagar_007";
}
public List<userProfile> getAllUsers(int limitStart, int limitMax) {
ResultSet rs = null;
String strsql = "select * from (select a.*, ROWNUM rnum from (select * from contestants order by user_id DESC) a where rownum <=" + Integer.toString(limitMax) + ") where rownum >=" + Integer.toString(limitStart) +"";
//String strsql = "select * from (select a.*, ROWNUM rnum from (select * from contestants order by user_id DESC) a where rownum <=" + Integer.toString(limitMax) + ") where rownum >=" + Integer.toString(limitStart) +"";
Connection conn = null;
try {
conn = CheckConnection();
conn.setAutoCommit(true);
PreparedStatement prepStatement = conn.prepareStatement(strsql);
rs = prepStatement.executeQuery();
while (rs.next()) {
userProfile user = new userProfile();
user.setUserid(rs.getString("user_id"));
user.setFirstName(rs.getString("firstName"));
user.setLastName(rs.getString("lastName"));
user.setEmailAddress(rs.getString("emailAddress"));
_collectionOfUserProfile.add(user);
}
} catch (SQLException ex) {
//handle catch
System.out.println(ex);
} finally {
closeConnection();
}
return _collectionOfUserProfile;
}
public boolean deleteUser(String userid){
boolean isSuccess = false;
ResultSet rs = null;
String strsql = "delete from contestant where UserID=?";
PreparedStatement prepStatement = null;
Connection conn = null;
try {
conn = CheckConnection();
conn.setAutoCommit(true);
int rtnCode = 0;
getDbConn().setAutoCommit(false);
prepStatement = conn.prepareStatement(strsql);
prepStatement.setString(1, userid);
rtnCode = prepStatement.executeUpdate();
if (rtnCode > 0) {
_dbConn.commit();
isSuccess =true;
}else{
_dbConn.rollback();
isSuccess = false;
}
} catch (SQLException ex) {
//catch handler
} finally {
closeConnection();
}
return isSuccess;
}
public int countTableDataRow(String TableName) {
TableName = "contestants";
int ValCount = 0;
Statement stmt = null;
Connection conn = null;
try {
conn = CheckConnection();
conn.setAutoCommit(true);
String strsql = "SELECT Count(*) FROM Contestants "; //+ TableName;
stmt = conn.createStatement();
try (ResultSet rs = stmt.executeQuery(strsql))
{
rs.next();
ValCount = rs.getInt(1);
}
} catch (SQLException se) {
//handle catch
} finally {
closeConnection();
}
return ValCount;
}
public void closeConnection() {
try {
if (_dbConn != null) {
_dbConn.close();
}
} catch (SQLException ex) {
//handle catch
}
}
public Connection CheckConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
LOGGER.info(e.getMessage());
}
Connection connection = null;
try {
connection = DriverManager.getConnection(_dbUrl, _user, _dbPassword);
} catch (SQLException e) {
LOGGER.info(e.getMessage());
}
if (connection != null) {
//LOGGER.info("You made it, take control your database now!");
} else {
LOGGER.info("Failed to make connection!");
}
return connection;
}
public List<userProfile> getCollectionOfUserProfile() {
return _collectionOfUserProfile;
}
public void setCollectionOfUserProfile(List<userProfile> collectionOfUserProfile) {
this._collectionOfUserProfile = collectionOfUserProfile;
}
}
DataGrid.jsp
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="TestPackage.userProfile"%>
<%@page import="TestPackage.userServices"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function ConfirmOnDelete(item) {
if (confirm("Are you sure to delete " + item + "?") === true)
return true;
else
return false;
}
</script>
</head>
<body>
<h1>Data Grid In JSP</h1>
<fieldset>
<legend>Users Management</legend>
${errorMessage}
${successMessage}
<div>
<form action="<c:url value="/dataGridServlet" />" method="POST">
<%
int limitStart = 0;
int limitMax = 15;
int pageSize = 15;
int allUserCount = 0;
int pageIndex = 0; //start page from index 0
session = request.getSession(false);
//check cookie
Cookie[] collectionCookies = request.getCookies();
String cookieValue = "";
for (Cookie c : collectionCookies) {
if (c.getName().equalsIgnoreCase("FirstTimeAccessUserManager")) {
if (c.getValue().equalsIgnoreCase("YES")) {
c.setValue("NO");
cookieValue = "NO";
} else if (c.getValue().equalsIgnoreCase("")) {
c.setValue("YES");
session.removeAttribute("limitStart");
session.removeAttribute("limitMax");
session.removeAttribute("pageIndex");
session.removeAttribute("pageSize");
}
}
}
if (cookieValue.equalsIgnoreCase("")) {
Cookie cookie = new Cookie("FirstTimeAccessUserManager", "YES");
response.addCookie(cookie);
}
if (session.getAttribute("limitStart") != null) {
limitStart = Integer.parseInt(session.getAttribute("limitStart").toString());
} else {
session.setAttribute("limitStart", limitStart);
}
if (session.getAttribute("limitMax") != null) {
limitMax = Integer.parseInt(session.getAttribute("limitMax").toString());
} else {
session.setAttribute("limitMax", limitMax);
}
if (session.getAttribute("pageIndex") != null) {
pageIndex = Integer.parseInt(session.getAttribute("pageIndex").toString());
} else {
session.setAttribute("pageIndex", pageIndex);
}
if (session.getAttribute("pageSize") != null) {
pageSize = Integer.parseInt(session.getAttribute("pageSize").toString());
} else {
session.setAttribute("pageSize", pageSize);
}
limitMax = pageSize;
userServices usersServ = new userServices();
List<userProfile> _collectionOfUserProfile = new ArrayList<userProfile>();
allUserCount = usersServ.countTableDataRow("usersprofile");
_collectionOfUserProfile = usersServ.getAllUsers(limitStart, limitMax);
String tableuser = "<table class=\"mainTable\" cellspacing=\"0\" rules=\"all\" id=\"MainContent_GridView1\" style=\"border-color:Gray;border-width:1px;border-style:Solid;width:95%;border-collapse:collapse;\">";
tableuser += "<tr style=\"color:White;background-color:#6699CC;font-weight:bold; padding:4px;\">";
tableuser += "<th scope=\"col\">No.</th>";
tableuser += "<th scope=\"col\">User ID</th>";
tableuser += "<th scope=\"col\">First Name</th>";
tableuser += "<th scope=\"col\">Last Name</th>";
tableuser += "<th scope=\"col\">Email</th>";
tableuser += "<th scope=\"col\"> </th>";
tableuser += "<th scope=\"col\"> </th></tr>";
int numberRecord = pageIndex * pageSize;
int balance = allUserCount - numberRecord;
int startRekodToShow = numberRecord + 1;
int index = startRekodToShow;
for (userProfile u : _collectionOfUserProfile) {
tableuser += "<tr style=\"border-color:Gray;border-width:1px;border-style:Solid;\">";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:20px;padding:4px;\">";
tableuser += Integer.toString(index);
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:100px;padding:4px;\">";
tableuser += u.getUserid();
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
tableuser += u.getFirstName();
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
tableuser += u.getLastName();
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:80px;padding:4px;\">";
tableuser += u.getEmailAddress();
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:50px;padding:4px;\">";
tableuser += "<input type=\"submit\" class=\"buttonLikeLink\" name=\"" + u.getUserid() + "\" onclick=\"return ConfirmOnDelete('" + u.getUserid() + "');\" value=\"Remove\" />";
tableuser += "</td>";
tableuser += "<td style=\"border-color:#CCCCCC;border-width:1px;border-style:Solid;width:50px;padding:4px;\">";
tableuser += "<input type=\"submit\" class=\"buttonLikeLink\" name=\"" + u.getUserid() + "\" value=\"Modify\" ></input>";
tableuser += "</td>";
tableuser += "</tr>";
index++;
}
tableuser += "</table>";
out.print(tableuser);
%>
</form>
<!-- Create logic next and previous in this section -->
<%
if (allUserCount > pageSize) {
String form = "";
if (pageIndex > 0) {
//form += "<h1>Page " + Integer.toString(pageIndex) + "</h1>";
}
form += "<form action=\"" + request.getContextPath() + "/navigateDatagrid\" method=\"POST\" >";
if (limitStart > 0) {
if (balance > pageSize) {
if ((pageSize + numberRecord) == allUserCount) {
//do not show next
} else {
//show next
form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
}
} else {
if ((balance + numberRecord) == allUserCount) {
//do not show next
} else {
//show next
form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
}
}
if (startRekodToShow != 1) {
form += "<input type=\"submit\" class=\"buttonNav\" id=\"bPrevious\" name=\"action\" value=\"Previous\" />";
}
} else {
form += "<input type=\"submit\" class=\"buttonNav\" id=\"bNext\" name=\"action\" value=\"Next\" />";
}
form += "</form>";
out.print(form);
}
%>
</div>
<%
if (allUserCount > 15) {
String grid_row_controller = "<div id=\"MainContent_PanelDropDownGVPage\" style=\"display:inline;\">";
grid_row_controller += "Total Users Per Page :";
grid_row_controller += "<form method=\"POST\" action=\"" + request.getContextPath() + "/navigateDatagrid\" id=\"pageRowform\" >";
grid_row_controller += "<select name=\"action\" style=\"width:50px;\" onchange=\"document.forms['pageRowform'].submit()\">";
if (pageSize == 10) {
grid_row_controller += "<option value=\"10\" selected=\"selected\">10</option>";
} else {
grid_row_controller += "<option value=\"10\">10</option>";
}
if (pageSize == 15) {
grid_row_controller += "<option selected=\"selected\" value=\"15\">15</option>";
} else {
grid_row_controller += "<option value=\"15\">15</option>";
}
if (pageSize == 25) {
grid_row_controller += "<option selected=\"selected\" value=\"25\">25</option>";
} else {
grid_row_controller += "<option value=\"25\">25</option>";
}
if (pageSize == 35) {
grid_row_controller += "<option selected=\"selected\" value=\"35\">35</option>";
} else {
grid_row_controller += "<option value=\"35\">35</option>";
}
if (pageSize == 50) {
grid_row_controller += "<option selected=\"selected\" value=\"50\">50</option>";
} else {
grid_row_controller += "<option value=\"50\">50</option>";
}
grid_row_controller += "</select>";
grid_row_controller += "</form>";
out.print(grid_row_controller);
}
%>
Show
<%
if (allUserCount > pageSize) {
if (pageIndex == 0) {
out.print("1 - " + pageSize);
} else {
if (balance > pageSize) {
out.print(startRekodToShow + " - " + (pageSize + numberRecord));
} else {
out.print(startRekodToShow + " - " + (balance + numberRecord));
}
}
} else if (allUserCount == 0) {
out.print("0");
} else {
out.print("1 - " + allUserCount);
}
%>
Record(s) From
<%
out.print(allUserCount);
%>
User(s)
</fieldset>
</body>
</html>
The issue being faced is when i access the DataGrid.jsp, the first page is able to show the data correctly however when i click next nothing shows. I am able to filter up to 25 records and all, but i cannot be able to view the next data when clicking next.
P.S I am using oracle database as the backend.
All help much appreciated.