Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Session in Java Servlet?

Tags:

java

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

Thank you very much.

like image 523
jl. Avatar asked Jan 11 '10 08:01

jl.


1 Answers

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.

like image 156
cletus Avatar answered Oct 13 '22 01:10

cletus