简体   繁体   English

在Java Servlet中使用会话

[英]Using Sessions in java servlet

can anyone tell me how to use sessions in login methods? 谁能告诉我如何在登录方法中使用会话? here my loging code and its working correctly.need to put sessions for that and don't know how.. 这是我的登录代码及其正常工作。需要为此设置会话,但不知道如何。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String operation = request.getParameter("operation");
    if(operation!=null && operation.equalsIgnoreCase("login")){
        loginDetail(request,response);
    }//else if(operation!=null && operation.equalsIgnoreCase("login")){
        //logout(request,response);
    //}
}

private void loginDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{


    User u = new User();
    UserService us =new UserServiceImpl() ;

    String Uname = request.getParameter("txtUname");        
    String Pwrd = request.getParameter("txtPwrd");  

    u.setUname(Uname);
    u.setPwrd(Pwrd);

    System.out.println(Uname+""+Pwrd);
    try {
        if(us.Userlogin(u.getUname(),u.getPwrd())){     
            String message = "Thank you, " + Uname +"..You are now logged into the system";
            HttpSession session = request.getSession(true);
            session.setAttribute("username", Uname);
            session.setAttribute("password", Pwrd);         
            response.setContentType("text/html");
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Menu.jsp").forward(request, response);
        }else {
            String message = "You have to register first or check Your user name password again!";              
            request.setAttribute("loginMsg", message);
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.jsp");
            rd.forward(request, response); 
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block          
        e.printStackTrace();
    }
}
}

I just put some lines of code inside "if(us.Userlogin(u.getUname(),u.getPwrd()))" statement..guide me through this piece of code 我只是在“ if(us.Userlogin(u.getUname(),u.getPwrd()))”语句中放了几行代码。

Did you mean that you want to login via the code you mentioned, and next time you don't want to login again to access the functionalities? 您是不是要通过提到的代码登录,而下次又不想再次登录以访问功能? So, you need to put a flag indicating the login status in the session object which span the life cycle of a specific time, eg, 30 minute. 因此,您需要在会话对象中放置一个表示登录状态的标志,该标志跨越特定时间(例如30分钟)的生命周期。 And the you put a filter to query the flag every time a request comes to determine if the client has logged. 然后,您将放置一个过滤器,以在每次请求确定客户端是否已登录时查询该标志。 It would be useful if you are doing a project for learning purpose. 如果您正在做一个学习项目,这将很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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