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>

    效果图

  • 相关阅读:
    Oracle RAC的五大优势及其劣势
    Lucene全文检索基础
    oracle手工生成AWR报告方法记录
    log file sync 等侍值高的一般通用解决办法
    log file sync 因为数据线有问题而造成高等侍的表现
    MongoDB实用教程
    1小时学会JQuery
    Ajax+Struts2实现验证码验证功能
    硬件01:门
    关于软件工程的思考15:人和绩效
  • 原文地址:https://www.cnblogs.com/zyt-bg/p/10637147.html
Copyright © 2011-2022 走看看