简体   繁体   中英

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.

you are setting it to session and reading it from request

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

您正在Session中设置属性并从Request获取它

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM