我将 java servlet 与数据库一起使用,但总是出现“索引 2 超出范围”的错误。我只想从表单发送参数名称和消息,并通过过程保存到数据库中。为什么我会收到此错误消息?
添加.jsp
<p>${result}</p>
<form action="Servlet" method="post">
<div class="comment-form">
<input type="hidden" name="action" value="4">
<p class="name">
<label>Name:</label>
<input type="text" name="name" value="${param.name}">
</p>
<p class="text">
<label>Message:</label>
<textarea name="message"></textarea>
</p>
<p class="submit">
<input type="submit" name="btnComment" value="Add">
</p>
</div>
</form>
Servlet.java
String name = request.getParameter("name");
String message = request.getParameter("message");
if (name == null || name.trim().equals("")) {
request.setAttribute("result", "Name missing!");
return "Add.jsp";
} else {
try {
con = comments.getConnection();
synchronized (con) {
stat = con.prepareCall("{CALL procAdd(?)}");
stat.setString(1, name);
stat.setString(2, message);
stat.executeUpdate();
}
request.setAttribute("result", "Comment added.");
return "Comments.jsp";
} catch (Exception e) {
request.setAttribute("result", "Error: " + e.getMessage());
return "Add.jsp";
}
过程 procAdd
CREATE PROCEDURE procAdd (
@Name VARCHAR (50),
@Message VARCHAR(50))
AS
BEGIN
INSERT INTO Comments(Name, Date, Message) VALUES (@Name, GETDATE(), @Message)
END