Question

I'am using jsp and servlet to realize the authentication before any access to the application The is the code of my doPost method:

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Account account;

        try {

            //Checking if the user already exists
            account = accountBesinessLocal.findByLogin(String.valueOf(username));
            if (account != null) {
                logger.log(Level.WARNING, "[User exists:{0}]", username);
                if (accountBesinessLocal.authentificateUser(String.valueOf(username), String.valueOf(password))) {
                    HttpSession session = request.getSession(true);
                    System.out.println(session);
                    session.setAttribute("username", account.getLogin());       
                    session.setAttribute("password", account.getPassword());  
                    System.out.println("this "+session.getAttribute(username)+" is connected");
                    response.sendRedirect(home.xhtml");
                } else {
                    request.setAttribute("erreur", "Incorrect Authentication");
                    getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
                }
            } else {
                request.setAttribute("erreur", "Incorrect Authentication");
                logger.log(Level.WARNING, "[User does not exist:{0}]", username);
                getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
            }
        } finally {
        }
    }

When i try to get the login of the user conneced with session.getAttribute(username); it returns null. How can i solve this?

Was it helpful?

Solution

You must use

session.getAttribute("username") 

and not

session.getAttribute(username)

the value of username is whatever the user has entered in the login input field. It's not "userame".

Side note: your code doesn't compile, s you might be running code that isn't the one ou posted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top