如何在Java Servlet中使用Session?

时间:2010-01-11 08:15:39

标签: java

我在java代码中遇到会话问题。在通过post提交表单后,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) {
    ...
}
...

非常感谢。

1 个答案:

答案 0 :(得分:8)

你需要的是:

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

您实际上并未在代码中的任何位置引用会话。

相关问题