Gretings 这是我大学的一个项目。我们的想法是提供一种功能,我们可以使用.JSP删除员工。
我尝试使用两个.jsp以及一些客户端Javascript
来实现此功能第一个jsp是数据的实际显示,在这个jsp上我有一个动态生成的表作为查询的结果。这是表的创建以及选择。 :
<%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=HR;user=sa;password=sa;");
Statement stmt = conn.createStatement();
String sqlStr = "SELECT EmpID, EmpFirstName, EmpLastName, EmpJobTitle, EmpSalary FROM Employees order by EmpID";
ResultSet rset = stmt.executeQuery(sqlStr);
%>
<table id ="tabEmployees" border=1>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th>Salary</th>
</tr>
<% while (rset.next()) { %>
<tr>
<td><%=rset.getInt("EmpID")%></td>
<td><%=rset.getString("EmpFirstName")%></td>
<td><%=rset.getString("EmpLastName")%></td>
<td><%=rset.getString("EmpJobTitle")%></td>
<td><%=rset.getDouble("EmpSalary")%></td>
<td><input type="submit" value="Delete" onclick="deleteRow(this)"> </td>
</tr>
<% } %>
</table>
正如您所看到的,我在每一行上都有一个删除按钮,其目的是删除该行(显然)。此删除按钮后面有一个javascript函数(deleteRow)。 javascript的代码位于.javascript文件中。这是:
function deleteRow(r)
{
var confirmation = confirm("Delete the row ?");
if (confirmation == true)
{
var i = r.parentNode.parentNode.rowIndex;
var tabEmployee = document.getElementById("tabEmployees");
var cellID = tabEmployee.rows[i].cells[0];
var empID = cellID.firstChild.data;
window.alert("1)The Emp id is = "+ empID);
var hidElement = document.getElementById("hidInput");
hidElement.value = empID;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("showDeleteResult").innerHTML = xhttp.responseText;
}
};
window.alert("2)The Emp id is = "+ empID);
xhttp.open("get", "deleteEmployees.jsp", true);
xhttp.send();
document.getElementById("tabEmployees").deleteRow(i);
}
}
最后我在另一个名为deleteEmployees.jsp的jsp上实际删除了数据,其中包含以下代码:
<body>
<%@ page import = "java.sql.*" %>
<%Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String empID = request.getParameter("empID");
SQLException ex1=null;
response.setContentType("text/html");
out.println("Employee ID " + empID);
try
{
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=HR;user=sa;password=sa;");
Statement stmt = conn.createStatement();
String delEmployee = "delete from dbo.Employees "
+ "where empID = " + empID;
stmt.executeUpdate (delEmployee);
stmt.close();
conn.close();
}
catch(SQLException ex)
{
ex1=ex;
}
if (ex1==null)
{
out.println("Employee Deleted");
}
else
{
out.println("Problem during the deletion of the employee ");
}
%>
</body>
虽然第一页上的EmpID在到达deleteEmployees.jsp时具有合法值,但是为空。这个empID如何保持其价值?
欢迎任何建设性的答案
谢谢
答案 0 :(得分:0)
您需要将empID作为请求参数传递给另一个jsp:
xhttp.open("get", "deleteEmployees.jsp?empID=" + empID, true);