zoukankan      html  css  js  c++  java
  • 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>

    效果图

  • 相关阅读:
    ubuntu: 环境搭建
    [转]unable to resolve superclass of 的奇怪问题和一种解决方法!
    [转]如何利用ndk-stack工具查看so库的调用堆栈【代码示例】?
    [转]TCP、UDP数据包大小的确定
    [转]教大家如何打造使用Tcpview(tcp查看器
    [转]帐号登录事件(事件编号与描述)
    [转]一个基于完成端口的TCP Server Framework,浅析IOCP
    [转]宏的高级使用--##,__VA_ARGS__, __FILE__, __FUNCTION__等
    mysql5.5 Replication 主从同步
    [转]adb pull Permission denied及no such file错误
  • 原文地址:https://www.cnblogs.com/zyt-bg/p/10637147.html
Copyright © 2011-2022 走看看