如何在Java Servlet中使用Session? [英] How to use Session in Java Servlet?

查看:312
本文介绍了如何在Java Servlet中使用Session?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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); 

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

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

这篇关于如何在Java Servlet中使用Session?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆