我正在使用 SimpleCaptcha 创建一个验证码输入,并验证了验证码输入。我使用以下代码创建了一个验证码输入。
HTML 代码:
<form action="submit_proceed.do" method="post">
<img src="captchaImg" /><input type="text" name="captcha" value=""><br />
<input type="submit" value="Submit" name="submit" />
</form>
JavaServlet 代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Iterator;
import nl.captcha.Captcha;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
List errorMsgs = new LinkedList();
try{
// Validate Captcha
HttpSession session = request.getSession(true);
String userCaptcha = request.getParameter("captcha");
Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
if (!captcha.isCorrect(userCaptcha)) {
errorMsgs.add("Please input the correct Captcha value.");
}
} catch (RuntimeException e) {
errorMsgs.add("An unexpected error: " + e.getMessage());
RequestDispatcher view = request.getRequestDispatcher("/error.view");
view.forward(request, response);
}
但是我一直收到此错误:
StandardWrapperValve[Captcha]: PWC1406: Servlet.service() for servlet Captcha threw exception
java.lang.IllegalStateException: PWC3999: Cannot create a session after the response has been committed
如何在我的 servlet 上创建会话?我该如何解决这个问题?
非常感谢你。