我有一个html页面,其中包含员工列表
<tr th:each="employee : ${employees}">
<td></td>
<td th:text="${employee.id}" ></td>
<td th:text="${employee.first}" ></td>
<td th:text="${employee.last}" ></td>
<td th:text="${employee.email}" ></td>
<td><a href="/employee/${employee.id}">Delete</a></td>
</tr>
控制器
@RequestMapping(value="/employee/{id}", method= RequestMethod.DELETE)
public String deleteEmployee(@PathVariable int id) {
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
String sql;
sql = "DELTE FROM salesforce.Employee__c WHERE Id = '"+ id +"'";
System.out.println(sql);
int result = stmt.executeUpdate(sql);
System.out.println("execute update returned: " + result);
}catch(Exception e){
e.printStackTrace();
}
return "redirect:/employees";
}
如何传递ID以便我可以删除特定员工?
由于
答案 0 :(得分:0)
您正在以正确的方式发送ID
public String deleteEmployee(@PathVariable(“id”) int id) {...}
但是,您的sql查询存在问题,因为您将给定的id作为字符串而不是整数进行比较。所以尽量使用 “......其中Id =”+ id
答案 1 :(得分:0)
尝试将您的Delete
链接更改为:
<a class="deleteLink" th:href="@{'/employee/' + ${employee.id}}">Delete</a>
控制器也需要一个小改动(检查我在代码中的注释):
@RequestMapping(value="/employee/{id}", method= RequestMethod.GET)
// "id" maybe not necessary but definitely a good practice
public String deleteEmployee(@PathVariable("id") int id) {
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
String sql;
// not sure you need to put param in ' ' here
// but you could try both varians and see if it makes any difference
sql = "DELETE FROM salesforce.Employee__c WHERE Id = "+ id;
System.out.println(sql);
int result = stmt.executeUpdate(sql);
System.out.println("execute update returned: " + result);
}catch(Exception e){
e.printStackTrace();
}
return "redirect:/employees";
}
我还将第一行更改为RequestMethod.GET
,以便点击链接。
但我不认为这是正确的方法。而不是这样做 - 最好留下RequestMethod.DELETE
,但是你需要一个javascript来处理这个链接点击并将DELETE方法发送到服务器。
我可以提供一个jQuery的例子,但不确定你是否正在使用它!但这只是我想说的一个例子:
$(".deleteLink").each(function (index) {
let path = $(this).attr("href");
$(this).click(function(e) {
e.preventDefault(); // prevent default behaviour
$.ajax({
url: path ,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
});
});
此代码可能需要一些修复,我不保证它有效!
希望这会有所帮助。
快乐编码:)