GVKun编程网logo

如何在Java中使用HttpSession跟踪登录尝试?(javabean跟踪用户会话)

27

如果您想了解如何在Java中使用HttpSession跟踪登录尝试?和javabean跟踪用户会话的知识,那么本篇文章将是您的不二之选。我们将深入剖析如何在Java中使用HttpSession跟踪登录

如果您想了解如何在Java中使用HttpSession跟踪登录尝试?javabean跟踪用户会话的知识,那么本篇文章将是您的不二之选。我们将深入剖析如何在Java中使用HttpSession跟踪登录尝试?的各个方面,并为您解答javabean跟踪用户会话的疑在这篇文章中,我们将为您介绍如何在Java中使用HttpSession跟踪登录尝试?的相关知识,同时也会详细的解释javabean跟踪用户会话的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

如何在Java中使用HttpSession跟踪登录尝试?(javabean跟踪用户会话)

如何在Java中使用HttpSession跟踪登录尝试?(javabean跟踪用户会话)

我有一个无框架的Web应用程序。我需要使用会话来实现一种检查不成功登录的简单方法。如果用户尝试使用不正确的用户名/密码组合登录3次,则会给他们20分钟的超时时间,然后才能再次尝试登录。

当前,只有在用户成功登录系统后,我才设置用户会话。但是,似乎我也应该在未成功登录的情况下进行会话,并以某种方式计算登录尝试次数。

Login.jsp(简体版):

<form name="loginForm" method="post" action="CustomerData">User name:<input type="text" name="userName"/>Password:<input type="password" name="password"/><input type="button" value="submit">

CustomerData.java(简化版):

// See if customer is a valid user        String selectQuery = "Select firstName,lastName,email from customer where userName=''"+userName+"'' and password=''"+password+"''";        selectResult = statement.executeQuery(selectQuery);if(selectResult.next()){    // We got a valid user, let''s log them in    ....    HttpSession session = request.getSession(true);    session.setAttribute("customer", customer);}else{    // this is where I need to get the session id (??),    // count the unsuccessful login attempts somehow,     //and give them a 20 minutes timeout before they can try logging in again.    request.setAttribute("message","Invalid username or password. Please try again!");}

在进行研究时,我发现各种Java框架都有很多内置的安全功能。我还发现使用会话不是跟踪登录尝试的最佳方法,因为用户可以使用不同的浏览器登录。但是,我正在为一个永远不会进入任何生产环境的简单Web项目创建此功能。我想知道如何使用Java
HTTPSession对象实现此功能。

好的,这是我收到的反馈的完整解决方案。我发布此信息是为了防止其他人遇到类似问题:

// See if customer is a valid userString selectQuery = "Select firstName,lastName,email from customer where userName=''"+userName+"'' and password=''"+password+"''";selectResult = statement.executeQuery(selectQuery);        if(selectResult.next())        {            // We got a valid user, let''s log them in            Customer customer = new Customer();            customer.setFirstName(selectResult.getString("firstName"));            customer.setLastName(selectResult.getString("lastName"));            customer.setEmail(selectResult.getString("email"));            customer.setUserName(userName);            customer.setPassword(password);            // establish a user session            session.setAttribute("customer", customer);            session.setAttribute("firstName", customer.getFristName());            url = "/index.jsp";            selectResult.close();        }        else        {            int loginAttempt;            if (session.getAttribute("loginCount") == null)            {                session.setAttribute("loginCount", 0);                loginAttempt = 0;            }            else            {                 loginAttempt = (Integer) session.getAttribute("loginCount");            }            //this is 3 attempt counting from 0,1,2            if (loginAttempt >= 2 )            {                        long lastAccessedTime = session.getLastAccessedTime();                date = new Date();                long currentTime = date.getTime();                long timeDiff = currentTime - lastAccessedTime;                // 20 minutes in milliseconds                  if (timeDiff >= 1200000)                {                    //invalidate user session, so they can try again                    session.invalidate();                }                else                {                     // Error message                      session.setAttribute("message","You have exceeded the 3 failed login attempt. Please try loggin in in 20 minutes, or call our customer service center at 1-800 555-1212.");                }            }            else            {                 loginAttempt++;                 int allowLogin = 3-loginAttempt;                 session.setAttribute("message","loginAttempt= "+loginAttempt+". Invalid username or password. You have "+allowLogin+" attempts remaining. Please try again! <br>Not a registered cusomer? Please <a href=\"register.jsp\">register</a>!");            }            session.setAttribute("loginCount",loginAttempt);            url = "/login.jsp";        }        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);        dispatcher.forward(request, response);

答案1

小编典典

您可以尝试以下代码

int loginAttempt = (Integer)session.getAttribute("loginCount");if (loginAttempt > 3 ){     // Error message/page redirection }else{     session.setAttribute("loginCount",loginAttempt++);}

c# – 如何在抽象类的静态属性中使用HttpContext.Current.Session.

c# – 如何在抽象类的静态属性中使用HttpContext.Current.Session.

我有一个ControllerBase抽象类,如下所示.

using System.Web;
using System.Web.Mvc;
public abstract class ControllerBase : Controller
{
    public static string SesssionId
    {
         get { return HttpContext.Current.Session["SessionId"]; }
    }
}

我收到了错误

“object reference is required for the non-static field,method,or
property ‘System.Web.Mvc.Controller.HttpContext.get”

但是我在其他静态类中使用了相同的并且没有出现上述错误.

我想知道HttpContext是如何可访问的而不是当前的.

谁能澄清我,上面有什么问题.

解决方法

您的基类Controller指定一个 HttpContext属性本身.
因此,在派生类ControllerBase中使用它时,编译器认为您要引用基类的此属性.

您可以使该属性非静态,如Wudzik在第一条评论中所建议的那样.
我想这将是更清洁的方式.

如果需要将此属性保持为静态,则必须告诉编译器,您要使用命名空间System.Web的HttpContext类:

public static string SesssionId
{
     get { return System.Web.HttpContext.Current.Session["SessionId"]; }
}

HttpSessionSecurityContextRepository - 没有 HttpSession,仅在 Chrome 中

HttpSessionSecurityContextRepository - 没有 HttpSession,仅在 Chrome 中

解决方案:

没有 SameSite 属性的 JSESSIONID cookie 被 Chrome 考虑以禁止在不同站点之间传递它。

因此 cookie 必须具有属性“SameSite=None; Secure”才能在站点之间传递它。
有时在 Chrome 中工作的原因是 Chrome 在前 1 或 2 分钟内在站点之间传递它。

需要 Attribute Secure 是因为 Chrome 认为在没有 SSL/TLS 上下文的站点之间传递 cookie 是不安全的。
考虑到对于本地测试/开发,您必须省略此属性或在 Firefox 浏览器上进行测试。

在java中的实现: 从 SavedRequestAwareAuthenticationSuccessHandler 覆盖方法中放入 onAuthenticationSuccess

Collection<String> headers = response.getHeaders(HttpHeaders.SET_COOKIE);
        boolean firstHeader = true;
        // there can be multiple Set-Cookie attributes
        for (String header : headers) {
            if (firstHeader) {
                response.setHeader(HttpHeaders.SET_COOKIE,String.format("%s; %s",header,"SameSite=None; Secure"));
                firstHeader = false;
                continue;
            }
            response.addHeader(HttpHeaders.SET_COOKIE,"SameSite=None; Secure"));
        }

感谢 jzheaux 为我指明了正确的方向!

希望它有帮助,我为此花了很多时间

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpSession;

一, 创建Servlet时候,当写入如下语句时:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

会提示你,程序包javax.servlet和程序包javax.servlet.http不存在的错误

2, 原因在于,java编译器没有找到软件包javax.servelt.

3, 解决的方法:把tomcat安装包里的lib目录下的servlet-api.jar拷贝一份到工程文件夹下的web目录下的WEB-INF目录下lib子文件下的,即 web—>WEB-INF–lib.

4、加入后记得buildpath, eclipse 和IDEA 方法不同.

eclipse,选中 相应jar包后右键 ->buildpath->add to build path

idea 参考:http://www.cnblogs.com/miller-zou/p/5495168.html

Java HttpSession

Java HttpSession

是在Java Servlet中仅在创建HttpSession之后

HttpSession s = request.getSession();

在我的代码中我没有写,但是当我使用时if (request.getSession(false) == null) ...,它不起作用。为什么?

答案1

小编典典

调用request.getSession()时创建一个HttpSession。

但是, 如果您默认访问JSP,它将自动创建一个会话。可以使用以下方式禁用此行为:<%@ page session="false">

您在使用JSP吗?

关于如何在Java中使用HttpSession跟踪登录尝试?javabean跟踪用户会话的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于c# – 如何在抽象类的静态属性中使用HttpContext.Current.Session.、HttpSessionSecurityContextRepository - 没有 HttpSession,仅在 Chrome 中、import javax.servlet.http.HttpSession;、Java HttpSession的相关知识,请在本站寻找。

本文标签: