如何在 Java Servlet 中使用 Session?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2040586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:05:55  来源:igfitidea点击:

How to use Session in Java Servlet?

java

提问by jl.

I am having issues with session in my java code. Upon submitting a form via post, the java servlet will determine if the captcha is correct. May I know anything that I should add to use the session in java servlet? Is there any thing that I need to import to use session?

我的 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) {
    ...
}
...

Thank you very much.

非常感谢你。

回答by cletus

Well you'll need:

那么你需要:

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

You're not actually referencing a session anywhere in your code.

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