如何在java中注销会话

时间:2016-04-18 05:58:40

标签: java jsp

public class LogoutController1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

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


        HttpSession session = request.getSession(false);

        if(session!=null){

            session.invalidate();
            session=null;
        }
        request.getRequestDispatcher("Login.jsp").forward(request,response);
    }
}
  1. 我的网站允许同时使用类似和不同的帐户进行多次登录。我尝试了每次登录的会话验证,但它无法正常工作。请帮我解决有关我网站的这个问题。
  2. 这个代码已经在这个网站上给出。我尝试使用相同的代码,但它没有用。问题是什么,请给我解决方案。

2 个答案:

答案 0 :(得分:0)

您需要设置身份验证属性。

Login.java

public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Login() {
        super();
    }
    Connection conn = null;
    String next="login.jsp";
    String uname,pwd;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        uname=request.getParameter("username");
        pwd=request.getParameter("password");
        HttpSession session = request.getSession(true);
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/intranet","root","root");
            Statement stmt=conn.createStatement();
            ResultSet rs=stmt.executeQuery("select * from login where username='"+uname+"' and password='"+pwd+"' ");
            if(rs != null){
                Member mem = new Member();
                if(rs.next()) 
                {
                    mem.setId(rs.getLong("id"));
                    mem.setFirstName(rs.getString("username"));
                    mem.setEmail(rs.getString("email"));
                    session.setAttribute("user", mem);
                    next = "index.jsp";
                }
                else
                {
                    next = "login.jsp";
                }
            }
        }
        catch(Exception ex)
        {
                System.out.println(ex);
        }
        finally
        {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            response.sendRedirect(next);
        }
    }
}

Logout.java

public class Logout extends HttpServlet {
    public Logout() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if(session.getAttribute("user") != null){
            session.removeAttribute("user");
            response.sendRedirect("login.jsp");
        }
    }

答案 1 :(得分:0)

您的代码仅显示Logout控制器的逻辑。确保Logincontroller有一些逻辑检查会话是否正在运行,如果是,则使当前会话无效。这可以通过在注销控制器中保存一些attirbute / flag并在登录控制器中检索它(验证标志/属性)并相应地进行来完成。