user3331487
user3331487

Reputation: 43

session getAttribute is null Java

I am trying login/logout validation with session

Here is the scenario I have a login.html which submits request to Login.java to validate username & password Once validated it goes to main.jsp which has logout button and form. I want to make sure that after logout with back button user should not see main.jsp or perform any action on form.

This is what I have in Login.java

public class Login extends HttpServlet {
    private ServletContext context=null;
    private RequestDispatcher dispatcher = null;
    private String toDo = "";  

    public void doPost(HttpServletRequest request,
              HttpServletResponse response)
                        throws IOException, ServletException  {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(PasswordUtilities.isValidLogin(username,password)) {
            toDo = "/jsp/main.jsp";

            HttpSession session = request.getSession();          
        session.setAttribute("username", "abc"); 
        System.out.println("login"+(String)request.getAttribute("username"));
            }
        else
            toDo = "/error.html";
        context = getServletContext();       
        dispatcher = context.getRequestDispatcher(toDo);
        dispatcher.forward(request, response);                  
    }    
}

but I'm getting the attribute null.

Please help, any help would be appreciated.

Upvotes: 0

Views: 3989

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240860

you are setting it to session and reading it from request

    session.setAttribute("username", "abc"); 
    System.out.println("login"+(String)request.getAttribute("username"));

Upvotes: 2

Puru--
Puru--

Reputation: 1111

You are setting attribute in Session and getting it from Request

System.out.println("login"+(String)request.getAttribute("username"));

Upvotes: 0

Related Questions