如何在Java Servlet中使用会话?

问题描述:

我在我的java代码中遇到了会话问题。通过邮件提交表单后,java servlet将确定验证码是否正确。我可以知道我应该添加什么来使用java servlet中的会话吗?有什么我需要导入使用会话吗?如何在Java Servlet中使用会话?

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
try{ 
    // Validate Captcha 
    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) { 
    ... 
} 
... 

非常感谢。

+3

请给出更多细节。特别是,“我有问题”非常模糊 - 请解释你所看到的。 – 2010-01-11 08:19:14

那么你将需要:

// create session if one doesn't exist 
HttpSession session = request.getSession(true); 

您实际上并不在你的代码引用一个会话的任何地方。

+0

我需要在“受保护的doPost(HttpServletRequest请求,HttpServletResponse响应)”中包含HttpSession吗? – 2010-01-11 08:22:25

+1

您需要导入javax.servlet.HttpSession,但如果您不这样做,javac将会投诉。 – cletus 2010-01-11 08:24:50

+0

非常感谢,有效。 – 2010-01-11 08:26:21