Cookie+mysql实现网易十天免登录【JAVAEE基础】

19.Cookie详解:

【了解】

1.Cookie  曲奇饼干
   - Cookie可以保存会话状态,会话状态是保留在客户端上。
   - 只要Cookie清除,或者Cookie失效,这个会话状态就没有了
   - Cookie是保存在浏览器客户端上的
   - Cookie 可以保存在浏览器缓存中,浏览器关闭Cookie消失
   - Cookie 也可以保存在客户端的硬盘文件中,浏览器关闭Cookie还在,除非Cookie失效。

2.Cookie不止在javaweb中。
  - 只要是web开发,只要是B/S架构的系统,只要是基于HTTP协议,就有Cookie的存在。
  - Cookie这种机制是HTTP协议规定的。

3.Cookie实现的功能
  - 保留购物车商品的状态在客户端上
  - 十天内免登录
  ....

【重点】

4.在java中Cookie被当作类来处理,使用new运算符可以创建Cookie对象,
   Cookie由两部分组成,name和value,都是字符串类型String。

5.在java程序中创建Cookie
   Cookie cookie =new Cookie(String cookieName,String cookieValue);

6.服务器可以一次向浏览器发送多个Cookie
   response.addCookie(cookie1);

7.默认情况下,服务器发送Cookie给浏览器之后,浏览器将Cookie保存在缓存当中,
  只要不关闭浏览器,Cookie永远存在,并且有效,当前浏览器关闭之后,缓存中的Cookie被清楚。

8. 在客户端保存的Cookie再次发送给服务器
   - 会不会提交发送Cookie给服务器,和请求路径有关系。
   - 不同的请求路径会发送提交不同的Cookie 

9.默认情况下,Cookie绑定的路径
   "/prj_servlet_12_war_exploded/test/createAndSendCookieToBrowser”  生成Cookie
   这个浏览器中的Cookie和"test/"路径绑定在一起,只要发送"test/"请求,Cookie就会提交给浏览器。

10.指定绑定路径
   cookie.setPath("/prj_servlet_12_war_exploded/king");
   只有发送"/prj_servlet_12_war_exploded/king" 请求路径,浏览器才会提交Cookie给服务器 

11.
   默认情况下,没有设置Cookie的有效时长,该Cookie默认保存在浏览器的缓存中,关闭浏览器,cookie消失
   
   设置Cookie的有效时长大于0,则该Cookie会被保存在客户端硬盘文件中。有效期一过,Cookie失效        
      cookie有效时长 = 0 直接被删除
	  cookie有效时长 < 0 不会被存储
	  cookie有效时长 > 0 存储在硬盘文件中

    cookie1.setMaxAge(60*60);//一小时有效

12.浏览器提交cookie给服务器,服务器接受cookie的方式:
      Cookie[] cookies = request.getCookies();    //从request对象中获取所有的Cookie

13.浏览器禁用Cookie:
    - 表示服务器发送的Cookie,浏览器不接收
    - 服务器还是会发送Cookie,只是浏览器不收。

14.使用Cookie实现十天内免登录

实现思路:

1.登录成功后,在loginServlet判断复选框选中,生成10天期限的cookie,发送给浏览器    
2.设置主页面为checkServlet检查是否存在cookie,从requst中获取所有cookie,并遍历。
   如果存在cookie,直接跳转到登陆成功页面,否则,跳转到登录页面。

上代码

登陆页面 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>网易十天内免登录页面</title>
</head>
<body>
    <form action="/prj_servlet_14_war_exploded/login" method="post">
        用户名<input type="text" name="username"><br>
        密码<input type="password" name="password"><br>
        <input type="checkbox" name="tenDaytoLoginFlog" value="ok">十天内免登录
        <br>
        <input type="submit" value="登录">
    </form>

</body>
</html>

检查登陆 CheckLoginServlet.java

package com.chif;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class CheckLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从request中获取所有的cookie
        Cookie[] cookies = req.getCookies();
        String username=null;
        String password=null;
        if (cookies!=null){
            //遍历cookie
            for (Cookie cookie:cookies){
                String cookiename = cookie.getName();
                String cookievalue = cookie.getValue();
                if("username".equals(cookiename)){
                    username=cookievalue;
                } else if ("password".equals(cookiename)){
                    password=cookievalue;
                }

            }
        }
        if (username!=null && password!=null){
            //连接数据库验证用户名和密码
            Connection conn=null;
            PreparedStatement ps=null;
            ResultSet rs=null;
            Boolean loginSuccess=false;
            String realname=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "105105");
                String sql="select  * from t_user where username= ? and password= ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                rs=ps.executeQuery();
                if (rs.next()){
                    realname = rs.getString("realname");
                    loginSuccess=true;
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (rs!=null){
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }if (ps!=null){
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }if (conn!=null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            //登陆成功或失败跳转
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter out = resp.getWriter();
            if (loginSuccess){
                //(动态页面)
                out.print(" <html>");
                out.print(" <head>");
                out.print(" <title>欢迎页面</title>   ");
                out.print(" </head>");
                out.print("  <body>");
                out.print(" 欢迎"+realname+"访问");
                out.print("  </body>");
                out.print(" </html>");
            } else {
                resp.sendRedirect(req.getContextPath()+"/login_error.html");
            }

        } else {
            //跳转到登陆页面
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }

    }
}

登陆 loginServlet.java

package com.chif;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");
        //获取用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //JDBC连接数据库验证用户名和密码
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        Boolean loginSuccess=false;
        String realname=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "105105");
            String sql="select  * from t_user where username= ? and password= ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs=ps.executeQuery();
            if (rs.next()){
                realname = rs.getString("realname");
                loginSuccess=true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if (ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //登陆成功或失败跳转
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (loginSuccess){
            //登录成功之后,获取复选框
            String tenDaytoLoginFlog = req.getParameter("tenDaytoLoginFlog");
            if ("ok".equals(tenDaytoLoginFlog)){
                //创建cookie对象
                Cookie cookie1 = new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);
                //设置有效时间
                cookie1.setMaxAge(60*60*24*10);
                cookie2.setMaxAge(60*60*24*10);
                //设置关联路径
                cookie1.setPath(req.getContextPath());
                cookie2.setPath(req.getContextPath());
                //发送cookie给浏览器
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }
            //(动态页面)
           out.print(" <html>");
           out.print(" <head>");
           out.print(" <title>欢迎页面</title>   ");
           out.print(" </head>");
           out.print("  <body>");
           out.print(" 欢迎"+realname+"访问");
           out.print("  </body>");
           out.print(" </html>");
        } else {
            resp.sendRedirect(req.getContextPath()+"/login_error.html");
        }

    }
}

在web.xml中设置检查登陆Servlet为主页面

   <welcome-file-list>
        <welcome-file>checklogin</welcome-file>
    </welcome-file-list>

SQL脚本

drop table if exists t_user;

create table t_user(
    id int(10) primary key auto_increment,
    username varchar(32) not  null unique ,
    password varchar(32) not  null ,
    realname varchar(128)
);

insert into t_user(username,password,realname) values ('admin','123','管理员');
insert into t_user(username,password,realname) values ('zhangsan','123','张三');
commit ;

运行页面
45
登录成功(勾选免登录,以后十天每次访问项目都是这个页面)
在这里插入图片描述
总结
网易十天登陆:利用cookie实现免登录,不安全,应该使用session实现。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值