I am using the standalone DataTables editor for fields in my web application. The creators of this software have PHP classes, but not java, so I hacked a fast Java servlet to accept incoming fields for editing. Javascript looks like this: (as you can see, there are different fields for the same URL)
editor = new $.fn.dataTable.Editor( {
ajax: "/json/fields/server",
fields: [ {
label: "Status:",
name: "status",
type: 'radio',
options: [
{ label: 'Enabled', value: 'Enabled' },
{ label: 'Disabled', value: 'Disabled' }
]
}, {
label: "Server IP address:",
name: "server-ip"
}, {
label: "Polling period:",
name: "poll-period"
}, {
name: "protocol",
type: "select",
options: [
{ label: 'TCP', value: 'TCP' },
{ label: 'UDP', value: 'UDP' }
]
}
]
} );
I use something like this in my Java servlet:
String serverid = request.getParameter("serverid");
String[] status = {"status", request.getParameter("data[keyless][status]")};
String[] server-ip = {"server-ip", request.getParameter("data[keyless][server-ip]")};
String[] protocol = {"protocol", request.getParameter("data[keyless][protocol]")};
String[][] fields = {status, server-ip, protocol};
Connection conn = null;
PreparedStatement pst = null;
String write = null;
try {
conn = ConnectionManager.getConnection();
for(String[] field : fields){
if(field[1] != null){
write = "{\"data\":[{\"" + field[0] + "\":\"" + field[1] + "\"}]}";
pst = conn.prepareStatement("UPDATE server SET " + field[0] + " = ? WHERE id = ?");
pst.setString(1, field[1]);
pst.setString(2, serverid);
pst.execute();
pst.close();
break;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.close(conn);
DBUtil.close(pst);
}
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
if(write != null)
writer.write(write);
writer.close();
I use an array of strings with a field name at first to protect against SQL injection, but I cannot use parameters because the field name is dynamic.
My question is: is there a better way to achieve this?