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>
Java Servlet 代码:
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上创建一个会话?我该如何解决这个问题?
非常感谢。
HttpSession session = request.getSession();
或类似语句在哪里?你如何获取session对象? - WildWezyr