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?
The following solutions uses Datatables server-side processing with ‘pre-filtering’ using a servlet.
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:
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.