How to create DataGrid or GridView in JSP - Servlet

Hi there, today I will like to share my knowledge on creating basic Datagrid in JSP.
This is my solution but not a permanent solution in all other cases. Maybe you can enhance this code to achieve your own objective. In this tutorial, I will use basic servlet and JSP.

Note: In this tutorial, I will use this library:-
  • MySQL JDBC Driver
  • JSTL 1.1
the project will run on source JDK 7

This is the database table

DROP TABLE IF EXISTS `blogtest`.`usersprofile`;
CREATE TABLE  `blogtest`.`usersprofile` (
  `userid` varchar(30) NOT NULL,
  `firstName` varchar(45) NOT NULL,
  `lastName` varchar(45) NOT NULL,
  `emailAddress` varchar(45) NOT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `usersprofile` VALUES ('Ahmad','Ahmad','Ahmad','Ahmad@gmail.com'),
('Ahmad1','Ahmad1','Ahmad1','Ahmad1@gmail.com'),
('Ahmad10','Ahmad10','Ahmad10','Ahmad10@gmail.com'),
('Ahmad11','Ahmad11','Ahmad11','Ahmad11@gmail.com'),
('Ahmad12','Ahmad12','Ahmad12','Ahmad12@gmail.com'),
('Ahmad13','Ahmad13','Ahmad13','Ahmad13@gmail.com'),
('Ahmad14','Ahmad14','Ahmad14','Ahmad14@gmail.com'),
('Ahmad15','Ahmad15','Ahmad15','Ahmad15@gmail.com'),
('Ahmad16','Ahmad16','Ahmad16','Ahmad16@gmail.com'),
('Ahmad2','Ahmad2','Ahmad2','Ahmad2@gmail.com'),
('Ahmad3','Ahmad3','Ahmad3','Ahmad3@gmail.com'),
('Ahmad4','Ahmad5','Ahmad5','Ahmad5@gmail.com'),
('Ahmad6','Ahmad6','Ahmad6','Ahmad6@gmail.com'),
('Ahmad7','Ahmad7','Ahmad7','Ahmad7@gmail.com'),
('Ahmad8','Ahmad8','Ahmad8','Ahmad8@gmail.com'),
('Ahmad9','Ahmad9','Ahmad9','Ahmad9@gmail.com');



The JSP Page

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="sys.userclass.userProfile"%>
<%@page import="sys.userclass.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>
        <br/>
        <br/>
        <fieldset>
            <legend>Users Management</legend>
            ${errorMessage}
            ${successMessage}
            <br/>
            <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\">&nbsp;</th>";
                          tableuser += "<th scope=\"col\">&nbsp;</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 = "<br/><br/>";
                    if (pageIndex > 0) {
                        form += "<h1>Page " + Integer.toString(pageIndex) + "</h1><br/>";
                    }
                    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>
        <br />
        <br />
        <%
            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);
            }
        %>       
        <br />
        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)
        <br />
    </fieldset>
</body>
</html>

The Navigator Data Grid Servlet

package sys.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
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 {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String buttonAction = request.getParameter("action");
        HttpSession session = request.getSession(false);
        int limitStart = 0;
        int limitMax = 15;
        int pageSize = 15;
        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 = 15;//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");
    }
}

The Edit Delete Servlet Data Grid

package sys.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sys.userclass.userServices;

public class dataGridServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
        String actionValue = "";
        String useridselected = "";
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
            useridselected = (String) en.nextElement();           
            actionValue = request.getParameter(useridselected); 
        }
        if(useridselected.trim().equalsIgnoreCase("")){
            request.setAttribute("errorMessage","Cannot find user id");
            request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
        }else{           
            if(actionValue.contains("Remove")){   
                userServices userServis = new userServices();
                if(userServis.deleteUser(useridselected)){
                    request.setAttribute("successMessage", "Successfully delete user: <b>" + useridselected + "</b>");
                    request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
                }else{
                    request.setAttribute("errorMessage", "Failed to delete user: <b>" + useridselected + "</b>, please try again");                   
                   request.getRequestDispatcher("/datagrid.jsp").forward(request, response);
                }               
            }else{
                //process redirect to modify user page with query string user id
                //redirect to modify page
       }
        }
    }
}

The UserServices Class

package sys.userclass;
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:mysql://localhost:3306/blogtest";
    private static String _user = "root";
    private static String _dbPassword = "P@ssw0rd";
    private final static Logger LOGGER = Logger.getLogger(userServices.class.getName());

    public userServices() {
        _collectionOfUserProfile = new ArrayList<>();
        _dbUrl = "jdbc:mysql://localhost:3306/blogtest";
        _user = "root";
        _dbPassword = "P@ssw0rd";     
    }
    public List<userProfile> getAllUsers(int limitStart, int limitMax) {
        ResultSet rs = null;
        String strsql = "Select * from usersprofile order by userid DESC limit " + Integer.toString(limitStart) + "," + Integer.toString(limitMax);
        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("userid"));
                user.setFirstName(rs.getString("firstName"));
                user.setLastName(rs.getString("lastName"));
                user.setEmailAddress(rs.getString("emailAddress"));
                _collectionOfUserProfile.add(user);
            }

        } catch (SQLException ex) {
            //handle catch
        } finally {
            closeConnection();
        }
        return _collectionOfUserProfile;

    }   

     public boolean deleteUser(String userid){
        boolean isSuccess = false;
        ResultSet rs = null;
        String strsql = "delete from usersprofile 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) {
        int ValCount = 0;
        Statement stmt = null;
        Connection conn = null;
        try {
            conn = CheckConnection();
            conn.setAutoCommit(true);
            String strsql = "SELECT Count(*) FROM " + 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("com.mysql.jdbc.Driver");
        } 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;
    }
}

The User Profile Class

package sys.userclass;
public class userProfile {
    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;
    }
}

Web.xml

 <servlet>
        <servlet-name>dataGridServlet</servlet-name>
        <servlet-class>sys.servlet.dataGridServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>navigateDatagrid</servlet-name>
        <servlet-class>sys.servlet.navigateDatagrid</servlet-class>
    </servlet>  
    <servlet-mapping>
        <servlet-name>dataGridServlet</servlet-name>
        <url-pattern>/dataGridServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>navigateDatagrid</servlet-name>
        <url-pattern>/navigateDatagrid</url-pattern>
    </servlet-mapping>

Output


NOTE: After doing all of this thing..you need to clear the cookie when you enter another page.
Use this code to clear the cookie when you enter another page.

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;
            }
        }
    }


Popular posts from this blog

How to create zip file to download in JSP- Servlet

Pinging in ASP.NET Example