我正在使用 datatables jquery 插件来表示使用 Servlet 的 JSP 页面中的数据库信息。我尝试按照以下教程进行操作:
http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications
在单击表单上的提交按钮后,我试图填充表格,经过几次尝试后我被卡住了。
小服务程序代码:
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);
}
}
此 servlet 生成以下 JSON 输出:
{"sEcho":0,"totalRecords":1,"TotalDisplayRecords":10,"aaData":[{"xxxx":"xxxx","xxx":"xxxxxx","xxxxxx":"xxxxxx","xxxxxx":"xxxxxxx"}]}
因为我使用了这个“结构”,所以我必须将以下代码添加到生成表的 .js 文件中。
JS文件:
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"}
]
});
};
我删除了 $(document).ready 行以使用 onClick 事件加载这只小狗。在我的 JSP 文件中,我有以下代码:
<%@ 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>
最好的办法是,如果我可以在加载 JSP 页面时生成一个空表,然后当我单击提交按钮时,该表将填充 servlet 返回的 JSON 数组的值。
关于如何实现这一目标的任何指示?