Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8065787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T11:46:31+00:00 2026-06-05T11:46:31+00:00

I am using the datatables jquery plug-in to represent database information within a JSP

  • 0

I am using the datatables jquery plug-in to represent database information within a JSP page using a Servlet. I tried to follow the following tutorial:

http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications

I am trying to populate the table after I click the submit button on a form, after a couples
of tries I am stuck.

servlet code:

package servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


import classes.DBConnection;

public class Search extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private int echo;
    private int totalrecords;
    private int totalDisplayRecords;

    public Search() 
    {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        String sEcho = request.getParameter("sEcho");

        Connection connect = new DBConnection().returnConnection();
        Map<String, String[]> parameters = request.getParameterMap();
        String sql = buildQuerytring(filterParameters(parameters));
        ResultSet rs = executeQuery(connect, sql);

        try {
            List<Object> aaData = buildAaData(rs);
            String JsonString = buildJsonResonse(aaData, sEcho);
            response.setContentType("application/Json");
            response.getWriter().print(JsonString);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private ResultSet executeQuery(Connection connect, String sql)
    {
        ResultSet rs = null;
        try {
            PreparedStatement presmt = connect.prepareStatement(sql);
            rs = presmt.executeQuery();
        } 
        catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    private String buildQuerytring(Map<String, String> map)
    {
        String select = "SELECT messagecaseid, messagesubject, messagesender, messagereceiver FROM berichtenarchief";
        StringBuilder sb  = new StringBuilder(select);
        boolean mapIsEmpty = map.isEmpty();

        if(mapIsEmpty == false)
        {
            int counter = 0;
            for(Map.Entry<String, String> entry : map.entrySet())
            {
                sb.append(" WHERE " + entry.getKey() + "=" + entry.getValue());
                counter++;
                if(counter > 1)
                {
                    sb.append(" AND " + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    private Map<String, String> filterParameters(Map<String, String[]> parameters)
    {
        Map<String, String> searchParameters = new HashMap<String, String>();
        for(Map.Entry<String, String[]> entry : parameters.entrySet())
        {
            String[] value = entry.getValue();
            if(value[0].isEmpty() == false)
            {
                searchParameters.put(entry.getKey(), value[0]);
            }
        }
        return searchParameters;
    }

    private List<Object> buildAaData(ResultSet rs) throws SQLException, JsonGenerationException, JsonMappingException, IOException
    {
        List<Object> JsonArray = new ArrayList<Object>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();
        int rowCounter = 0;

        while(rs.next())
        {
            Map<String, Object> JsonObject = new LinkedHashMap<String, Object>();
            for(int colCounter = 1; colCounter<=colCount; colCounter++)
            {
                String JsonString = rsmd.getColumnName(colCounter);
                String JsonValue = rs.getObject(colCounter).toString();
                JsonObject.put(JsonString, JsonValue);
            }
            JsonArray.add(JsonObject);
            rowCounter++;
        }
        this.totalrecords = rowCounter;
        return JsonArray;
    }

    private String buildJsonResonse(List<Object> aaData, String sEcho) throws JsonGenerationException, JsonMappingException, IOException
    {
        totalDisplayRecords = 10;
        Map<String, Object> jsonObject = new LinkedHashMap<String, Object>();
        ObjectMapper mapper = new ObjectMapper();

        jsonObject.put("sEcho", echo);
        jsonObject.put("totalRecords", totalrecords);
        jsonObject.put("TotalDisplayRecords", totalDisplayRecords);
        jsonObject.put("aaData", aaData);

        return mapper.writeValueAsString(jsonObject);
    }
}

this servlets generates the following JSON output:

{"sEcho":0,"totalRecords":1,"TotalDisplayRecords":10,"aaData":[{"xxxx":"xxxx","xxx":"xxxxxx","xxxxxx":"xxxxxx","xxxxxx":"xxxxxxx"}]}

Because I used this “structure” I had to add the following code to the .js file that generates the table.

JS file:

function generateTable () {
    $("#searchResults").dataTable({
        "bFilter" : false,
        "bServerSide": true,
        "sAjaxSource": "/ArchiveSearch/Search",
        "bProcessing": true,
        "sPaginationType": "full_numbers",
        "bJQueryUI": true,
        "aoColumns":    [
                                {"mDataProp": "xxxxxxxx"},
                                {"mDataProp" : "xxxxxxx"},
                                {"mDataProp" : "xxxxxxxx"},
                                {"mDataProp" : "xxxxxx"}
                            ]
        });
    };

I removed the $(document).ready line to load this puppy with an onClick event.
In my JSP file I have the following code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <link href="/ArchiveSearch/resources/css/style.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="/ArchiveSearch/resources/js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="/ArchiveSearch/resources/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" scr="/ArchiveSearch/resources/js/datatablesConfig.js"></script>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>searchArchive</title>
</head>
<body>
        <div class="wrapper">
        <div class="navmenu">
            <ol>
                <li><a href="index.jsp" >Home</a></li>
                <li><a href="connection.jsp" >Archive Connection</a></li>
                <li><a class="current" href="searchArchive.jsp">Zoeken in archief</a></li>
            </ol>
        </div>
        <div class="content">
            <form action="/ArchiveSearch/Search" method="post">
            <div class="searchCiteria">
                <div id="searchValueBlock1">
                        <div><span class="label">xxxxxx:</span><input type="text" name="xxxxx"  size="25"/></div>
                        <div><span class="label">xxxxxx:</span><input type="text" name="xxxx" size="25" /></div>
                        <div><span class="label">xxxxxxx:</span><input type="text" name="xxxxxx"  size="25"/></div>
                        <div><span class="label">xxxxxxx:</span><input type="text" name="xxxxxxxx"  size="25"/></div>
                </div>

                <div id= "searchValueBlock2">
                    <div><span class="label">xxxxxxxx:</span><input type="text" name="xxxxxx"  size="25"/></div>
                    <div><span class="label"></span><input type="text" name="xxxxxx"  size="25"/></div>

                    <div class="submit">
                        <input type="submit" value="Search" onclick="generateTable()">
                    </div>
                </div>
            </div>
            </form>
            <div class="result">
                <div id="demo_jui">
                    <table id="searchResults">
                        <thead>
                            <tr>
                                <th>xxxxxxx</th>
                                <th>xxxxxxx</th>
                                <th>xxxxxxx</th>
                                <th>xxxxxxxx</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

The best thing would be if I can make so that an empty table is generated when the JSP pages is loaded, then when I click the submit button the table is populated with the values of the JSON array returned by the servlets.

Any pointers on how I can achieve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T11:46:34+00:00Added an answer on June 5, 2026 at 11:46 am

    The following solutions uses Datatables server-side processing with ‘pre-filtering’ using a servlet.

    Servlet code:
    
    package servlets;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.codehaus.jackson.JsonGenerationException;
    import org.codehaus.jackson.map.JsonMappingException;
    import org.codehaus.jackson.map.ObjectMapper;
    
    
    import classes.DBConnection;
    
    public class Search extends HttpServlet
    {
        private static final long serialVersionUID = 1L;
        private int echo;
        private int totalrecords;
        private int totalDisplayRecords;
    
        public Search() 
        {
            super();
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
            Connection connect = new DBConnection().returnConnection();
            System.out.println(request.getParameter("formData"));
            Map<String, String> searchParameterMap = seperateFormString(request.getParameter("formData"));
            echo = Integer.parseInt(request.getParameter("sEcho"));
            String sql = buildQuerytring(searchParameterMap);
            ResultSet rs = executeQuery(connect, sql);
    
    
            try {
                List<Object> aaData = buildAaData(rs);
                String JsonString = buildJsonResonse(aaData, echo);
                response.setContentType("text/x-json;charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                response.getWriter().print(JsonString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
        private Map<String, String> seperateFormString(String formData){
    
            Map<String, String> searchParameterMap = new HashMap<String, String>();
            String[] strings = formData.split("&");
            for(String s : strings)
            {
                String[] parameters = s.split("=");
                int value = parameters.length-1;
                if(parameters.length>1){
                    searchParameterMap.put(parameters[0], parameters[value]);
                }
            }
            return searchParameterMap;
        }
    
        private ResultSet executeQuery(Connection connect, String sql)
        {
            ResultSet rs = null;
            try {
                PreparedStatement presmt = connect.prepareStatement(sql);
                rs = presmt.executeQuery();
            } 
            catch (SQLException e) {
                e.printStackTrace();
            }
            return rs;
        }
    
        private String buildQuerytring(Map<String, String> map)
        {
            String select = "SELECT messagecaseid, messagesubject, messagesender, messagereceiver FROM berichtenarchief";
            StringBuilder sb  = new StringBuilder(select);
            boolean mapIsEmpty = map.isEmpty();
            int counter = 0;
    
            if(mapIsEmpty == false)
            {
                for(Map.Entry<String, String> entry : map.entrySet())
                {
                    if(counter >= 1)
                    {
                        sb.append(" AND " + entry.getKey() + " LIKE " + "'%" + entry.getValue() + "%'");
                    }
                    else if(counter == 0)
                    {
                        sb.append(" WHERE " + entry.getKey() + " LIKE " + "'%" + entry.getValue() + "%'");
                    }
                    counter++;
                }
            }
            System.out.println(sb.toString());
            return sb.toString();
        }
    
        private List<Object> buildAaData(ResultSet rs) throws SQLException, JsonGenerationException, JsonMappingException, IOException
        {
            List<Object> JsonArray = new ArrayList<Object>();
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            int rowCounter = 0;
    
            while(rs.next())
            {
                Map<String, Object> JsonObject = new LinkedHashMap<String, Object>();
                for(int colCounter = 1; colCounter<=colCount; colCounter++)
                {
                    String JsonString = rsmd.getColumnName(colCounter);
                    String JsonValue = rs.getObject(colCounter).toString();
                    JsonObject.put(JsonString, JsonValue);
                }
                JsonArray.add(JsonObject);
                rowCounter++;
            }
            this.totalrecords = rowCounter;
            return JsonArray;
        }
    
        private String buildJsonResonse(List<Object> aaData, int echo) throws JsonGenerationException, JsonMappingException, IOException
        {
            totalDisplayRecords = 10;
            Map<String, Object> jsonObject = new LinkedHashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
    
            jsonObject.put("sEcho", echo);
            jsonObject.put("iTotalRecords ", totalrecords);
            jsonObject.put("iTotalDisplayRecords ", totalDisplayRecords);
            jsonObject.put("aaData", aaData);
    
            return mapper.writeValueAsString(jsonObject);
        }
    }
    

    Information from form with server-side processing, and a popup with data from the selected row which can be used for other things you need.

    JQuery code:

    var table;
    var gaiSelected =  [];
    
    $(document).ready(function() {
        $("#searchResults").dataTable({
            "bJQueryUI": true
            });
        $('.searchsubmit').click(function() {
            var formData = $('form').serialize();
            table = $("#searchResults").dataTable({
                "bDestroy": true,
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": 'Search',
                "sServerMethod": "POST",
                "aoColumns": [
                              { "mDataProp": "xxxxxxx" },
                              { "mDataProp": "xxxxxxx" },
                              { "mDataProp": "xxxxxxxx" },
                              { "mDataProp": "xxxxxxxxx" }
                          ],
                "fnServerParams": function ( aoData ) {
                    aoData.push({"name": "formData", "value": formData}
                            );
                }
            });
            return false;
        });
    
         $('#searchResults tbody tr').live('dblclick', function () {
             var aData = table.fnGetData( this,0 );
             alert(aData);
                });
    });
    

    IMPORTANT: use return false at the end of your onClick method. thanks somebody for pointing that out. (I will try to find you later and give some points.) Further touti, Succes parameter is not necessary, see Jquery doc.

    If I think of something important later, I will add this to the post later.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using a jQuery plug-in called Datatables on a table contained within a
I'm using jQuery datatables plug-in on my HTML Table. I wanted to know how
I'm using the jQuery DataTables plug-in for my HTML table. Is there a way
We're using the jQuery DataTables plug-in . The plug-in seems to be quite a
I am using jQuery templates and the dataTables plug-in to create grids in my
I am using jQuery datatables in a dynamic PHP site. I have a page
I've been using the DataTables jQuery plugin with the filter plug in, and it
I'm using the marvellous DataTables jQuery plug-in; http://datatables.net/ Added the FixedColumns and KeyTable extras.
I'm trying to use the DataTables jQuery plug-in in MVC3 using an ajax request
I am using the jQuery plug-in Datatables , is it possible to change the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.