Servlet Cookie如何实现记住密码,自动登录的效果呢?

java-教程王 Servlet 发布时间:2021-12-13 09:45:33 阅读数:16226 1
下文笔者讲述Servlet使用Cookie技术,实现密码记录及自动登录的效果分享,如下所示:
实现思路:
     1.将登录所使用的账号及密码存入到客户端的Cookie中
	 2.Servlet加载时,自动加载Cookie并使用其中的账号和密码,然后根据相应的逻辑实现自动登录操作
例:
//login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录</title>
<%
    String username = "";
    String password = "";
    //获取当前站点的所有Cookie
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {//对cookies中的数据进行遍历,找到用户名、密码的数据
        if ("username".equals(cookies[i].getName())) {
            username = cookies[i].getValue();
        } else if ("password".equals(cookies[i].getName())) {
            password = cookies[i].getValue();
        }
    }
%>
</head>
<body>
    <form action="login_handler.jsp" method="post">
        username:<input type="text" name="name" value="<%=username%>" /><br/>
        password:<input type="password" name="pwd" value="<%=password%>" /><br/>
        <input type="checkbox" value="y" name="isLogin">自动登录<br/> 
        <input type="submit" value="登录" />
    </form>
</body>
</html>

//login_handler.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    String name = request.getParameter("name");
    String pwd = request.getParameter("pwd");
    String flag = request.getParameter("isLogin");

    if (!"admin".equals(name) && !"pwd123456".equals(pwd)) {
        response.sendRedirect("error.jsp");
    } else {
        if ("y".equals(flag)) {
            //创建两个Cookie对象
            Cookie nameCookie = new Cookie("username", name);
            //设置Cookie的有效期为3天
            nameCookie.setMaxAge(60 * 60 * 24 * 3);
            Cookie pwdCookie = new Cookie("password", pwd);
            pwdCookie.setMaxAge(60 * 60 * 24 * 3);
            response.addCookie(nameCookie);
            response.addCookie(pwdCookie);
        }
        response.sendRedirect("success.jsp");
    }
%>


//success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Succes成功</title>
</head>
<body>success.
</body>
</html> 

//error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>error错误</title>
</head>
<body>error.
</body>
</html>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/Servlet/202112/232.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者