如何在Javaservlet中使用会话?

如何在Javaservlet中使用会话?,java,Java,我的java代码中的会话有问题。通过post提交表单后,Javaservlet将确定验证码是否正确。我可以知道在JavaServlet中使用会话需要添加什么吗?有什么东西需要导入才能使用会话吗 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ // Validate Captcha S

我的java代码中的会话有问题。通过post提交表单后,Javaservlet将确定验证码是否正确。我可以知道在JavaServlet中使用会话需要添加什么吗?有什么东西需要导入才能使用会话吗

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) {
    ...
}
...
非常感谢。

您需要:

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

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

请提供更多详细信息。特别是,“我有问题”非常模糊-请解释您看到的情况。我是否需要在“受保护的doPost(HttpServletRequest,HttpServletResponse)”中包含HttpSession?您需要导入javax.servlet.HttpSession,但如果您不这样做,javac会抱怨。不知道这是否不同,因为新版本,但是现在我不得不
导入javax.servlet.http.HttpSession
,而不是
javax.servlet.HttpSession
,只是为了完整性。