有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用会话和cookie的Javaservlet身份验证

我需要实现简单的servlet用户身份验证(在Java Dynamic Web项目中),但有些事情让我有点困惑

首先,servlet出于某种原因创建cookie JSESSIONID,尽管我从未要求它这样做。而且,我不能改变它的值,如果我改变request.addCookie(new Cookie("JSESSIONID", session.getId())),它会产生如下结果:

Cookie: JSESSIONID=6B5B441038414B4381EDB7470018F90E; JSESSIONID=7890D45DF445635C49BDEB3CADA8AD99; .......

因此,它复制了cookie

其次,我不确定在哪里比较cookie和会话id,以及在哪里以及如何正确创建会话(即request.getSession(true? / false? / nothing?);

我已经阅读了一些文档,但仍然需要帮助


我有一个servlet HomeServlet,如果用户没有经过身份验证,它应该将用户重定向到authentication页面

我是这样做的(HomeServlet.java):

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

        if(request.getSession().getAttribute("user") != null) {
            request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
        } else {
            response.sendRedirect("authentication");
        }
    }

我还有AuthServlet,它为jsp页面提供身份验证表单并验证用户

AuthServlet.java

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

    String action = request.getParameter("ACTION");

    if ("login".equals(action)) {
        String[] result = doSomeValidations();

        if (result.size() > 0) { // show validation errors
            request.setAttribute("errorLoginMessage", result);
            request.setAttribute("email", email);
            doGet(request, response);
        } else { // authenticate user
            request.getSession().setAttribute("user", userObject);
            request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
        }
    } else if ("signup".equals(action)) {
        // ...........................          
    } else {
        doGet(request, response);
    }
}

那么,你能帮我理解这一点吗?如何实现用户身份验证并在整个会话中保持用户登录


共 (1) 个答案

  1. # 1 楼答案

    Firstly, the servlet for some reason creates the cookie JSESSIONID although I never ask it to

    HttpSession jsession = request.getSession();  
    

    您正在这里请求会话,容器将创建JSESSIONIDcookie作为响应

    how to create session correctly request.getSession(true? / false? / nothing?);

    request.getSession()request.getSession(true)完全一样,如果需要,它们会启动一个新会话,但是request.getSession(false)意味着如果已经有会话,就使用它,如果没有会话,就不要启动。 如何以及在何处开始会话完全取决于您的需求

     response.addCookie(new Cookie("JSESSIONID", jsession.getId()));
    

    不支持您自己添加JSESSIONIDcookie,容器将为您执行此操作

    您还应该在应用程序中创建一次会话,一旦用户浏览器中存储了JSESSIONIDcookie(如果启用了cookie),它将与请求一起发送

    How do I implement user authentication

    非常主观,取决于需求,您可以阅读此https://docs.oracle.com/cd/E19226-01/820-7627/bncby/index.html

    keep the user logged in throughout the session

    一旦用户通过身份验证,您的会话cookie将帮助您实现这一点,例如登录facebook并打开cookies选项卡