Ciao,
qualcuno ha mai provato a popolare una datatable (
https://datatables.net) da mysql?
non riesco a farlo.. ho provato a creare una servlet che restituisce un GSON, ma non funziona.
Sinceramente è la prima volta che uso i json, e a debuggare non son bravo.. non riesco a verificare che la tabella faccia l'ajax call verso la servlet..
qualcuno conosce un esempio funzionante?
mi basterebbe che l'esempio prenda i dati da un db mysql (anche in php) per iniziare a capire qualcosa..
vi posto il codice che ho usato.
JSP
Codice:
<div id="main_content_table">
<table id="mytable">
<thead>
<tr>
<th>id</th>
<th>desc</th>
<th>model</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#mytable").dataTable( {
"bProcessing": false,
"bServerSide": false,
"sAjaxSource": "./PopulateTableDevice",
"bJQueryUI": true,
"aoColumns": [
{ "mData": "id" },
{ "mData": "desc" },
{ "mData": "model" }
]
} );
} );
</script>
Servlet PopulateTableDevice
Codice:
@WebServlet("/PopulateTableDevice")
public class PopulateTableDevice extends HttpServlet {
private static final long serialVersionUID = 1L;
public PopulateTableDevice() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
List<DeviceBean> deviceList = DeviceDaoBean.getAllDevice();
DataTableDevice dtd = new DataTableDevice();
dtd.setAaData(deviceList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dtd);
out.print(json);
}
}
DeviceBean
Codice:
public class DeviceBean {
private Integer id;
private String desc;
private String model;
... getter and setter...
DeviceDaoBean
Codice:
public class DeviceDaoBean {
static Connection currentCon = null;
static ResultSet rs = null;
public static ArrayList<DeviceBean> getAllDevice() {
Statement stmt = null;
String searchQuery = "select * from DEVICE";
ArrayList<DeviceBean> deviceList = new ArrayList<DeviceBean>();
try {
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
while(rs.next()) {
DeviceBean device = new DeviceBean();
device.setDesc(rs.getString("DESC"));
device.setId(rs.getInt("ID"));
device.setModel(rs.getInt("MODEL"));
deviceList.add(device);
}
ConnectionManager.closeConnection(currentCon, stmt);
rs.close();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return deviceList;
}
}
MySQL table
Codice:
CREATE TABLE DEVICE
(
ID INT NOT NULL AUTO_INCREMENT,
DESC CHAR(255) CHARACTER SET utf8,
MODEL CHAR(255) CHARACTER SET utf8,
PRIMARY KEY (ID)
);
Grazie.