我已经编写了delete方法的servlet和dao部分。 一旦我想在jsp页面中使用该方法,它将返回ERROR 500 / ERROR 404。
我正在使用tomcat 7,Java 7和Windows10。正在运行oracle。我尝试使用ajax链接servlet删除方法,但仍然无法正常工作。
// deleteStaffServelt
public class DeleteStaffServlet extends HttpServlet {
enter code here
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ids = request.getParameter("userId");
int deleteId = Integer.parseInt(ids);
StaffDao staffDao = new StaffDao();
staffDao.delete(deleteId);
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// delete method in Dao
public void delete(int id) {
try {
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID = " + id;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// jsp
<body>
<form action="listServletTwo">
<table border="0" cellspacing="0">
<tr>
<td>社員No. <input name="noStart" type="text" size="8" />
~ <input name="noEnd" type="text" size="8" /> <input
type="submit" value="検索" />
</td>
<td>社員名. <input name="name" type="text" size="20" /> <input
type="submit" value="検索" />
</td>
</tr>
</table>
</br>
<%
List<Staff> list1 = (List<Staff>) session.getAttribute("list");
if (list1 != null) {
%>
<table border="1" cellspacing="0">
<tr bgcolor="pink">
<td>社員No.</td>
<td>ユーザーID</td>
<td>社員名</td>
<td>削除機能</td>
<td>更新機能</td>
</tr>
<%
for (Staff s : list1) {
%>
<tr>
<td id="<%=s.getId()%>"><%=s.getId()%></td>
<td><%=s.getNo()%></td>
<td><%=s.getName()%></td>
<td><a href="deleteStaffServlet?id=<%=s.getId()%>" name="userId">Delete</a></td>
<td>名前:<input name="name" type="text" size="10" /> ユーザーID:<input
name="name" type="text" size="10" />
<input type="submit" value="Edit" name="edit" onclick="editRecord(<%=s.getId()%>);">
</td>
</tr>
<%
}
}
session.removeAttribute("list");
%>
</table>
</form>
结果为HTTP状态500 –内部服务器错误 java.lang.NumberFormatException:空
答案 0 :(得分:1)
在这里,<a href="deleteStaffServlet?id=<%=s.getId()%>" name="userId">Delete</a>
,您已经使用过id=<%=s.getId()%>
,即:您正在参数<%=s.getId()%>
中获得值id
,但是在您的servlet
中,您正在获取参数使用request.getParameter("userId");
只需将其更改为request.getParameter("id");
。
此外,您的delete query
是错误的,如下所示:
// delete method in Dao
public void delete(int id) {
try {
//you have to give placeholder(?) in query not the value
String sql = "delete from ZZZ_EMPLOYEES where ZE_ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
我不确定您在这里做什么:
response.sendRedirect("deleteStaffServlet?id=" + deleteId);
但是,我认为您已经从表中删除了必需的row
,因此无需再次执行此操作。因此,只需将其更改为以下内容即可:
response.sendRedirect("yourjsppage");