2010-01-11 53 views
3

我在我的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

回答

6

那麼你將需要:

// 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