java web实现在cookie中保存用户名和密码,用户自动登入

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie使用的简单例子/title>
</head>
<body

> <% Cookie[] cook = request.getCookies();//获取本地所有的Cookie对象 String[] userMessage = new String[] { "", "" }; //用户存储从cookie中获取的用户名和密码 if (cook != null) { for (int i = 0; i < cook.length; i++) { if (cook[i].getName().equals("userInfo")) { userMessage = cook[i].getValue().split("#");//通过分割split获取用户名和密码. } } } %> <p>本页面仅用于测试,只有输入用户名为张运涛,密码为123456时,提示正常登录,否则提示用户名密码错误;正常登入后会把用户名与密码保存在cookie中便于用户登入</p> <form action="check.jsp" method="post"> <table> <tr> <td>用户名:</td> <td><input name="userName" type="text" value="<%=userMessage[0]%>"></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password" value="<%=userMessage[1]%>"></td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交">&nbsp;<input type="reset" value="重置"></td> </tr> </table> </form> </body> </html>

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <%
        request.setCharacterEncoding("utf-8");

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        if (userName.equals("张运涛") && password.equals("123456")) {
            Cookie mycook=new Cookie("userInfo",userName+"#"+password);  //设置cookie对象
            mycook.setMaxAge(60*60*20*365); //设置cookie有效期
            response.addCookie(mycook);//把cookie对象发送到客户端进行存储
    %>

    <script>
        alert("登录成功!");
        window.location.href = "login.jsp";
    </script>

    <%
        } else {
    %>
    <script>
        alert("登录失败,用户名或者密码错误");
        window.location.href = "login.jsp";
    </script>

    <%
        }
    %>




</body>
</html>

效果图

 

转载于:https://www.cnblogs.com/zyt-bg/p/10637147.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值