Cookie:实现网站十天内免密登录

一、Cookie是什么:

session的实现原理中,每一个session对象都会关联一个sessionid,例如:jsessionid=xxxxxxxxxxxx
以上的这个键值对数据其实就是cookie对象。

二、Cookie作用:

  1. cookie和session机制其实都是为了保存会话状态
  2. cookie是将会话的状态保存在浏览器客户端上。(cookie数据存储在浏览器客户端上的)
  3. session是将会话的状态保存在服务器端上。(session对象是存储在服务器上)
  4. cookie是保存在浏览器上的key=value键值对,可以保存账号密码sessionid等,根据需求在需要的地方创建cookie。 只要浏览器不关闭,用户再次发送请求的时候,会根据URL在request请求的请求头中自动将部分需要的cookie发送给服务器。
  5. 为什么要有cookie和session机制呢?因为HTTP协议是无状态协议。

三、Cookie保存在什么地方?

  1. 可以保存在浏览器运行内存中。(浏览器只要关闭cookie就消失了)
  2. 可以保存在硬盘文件中。(永久保存。)

四、Cookie和Session区别:

一个保存在浏览器客户端,一个保存在服务器端。

四、Cookie用法:

位于jakarta.servlet.http.Cookie包下;

  1. 创建cookie对象:
new Cookie(key,value);
  1. java程序把cookie数据发送给浏览器:
response.addCookie(cookie对象)
  1. 设置cookie失效时间:
    只要设置了cookie失效时间,这个cookie就会存储在硬盘文件中。不设置就会存储在浏览器运行内存中,浏览器关闭cookie失效。
cookie.setMaxAge(s);//秒为单位
  1. 删除该cookie:
cookie.setMaxAge(0);
  1. 设置cookie接收路径:
    表示只要URL请求路径是servlet13下的路径,浏览器都会发送这个cookie给服务器。
    系统默认设置是生成cookie的路径(/servlet13/abc/list)的上一层路径(servlet13/abc)。
cookie.setPath("/servlet13")
  1. 获取浏览器发送给服务器的cookie:
    如果没有接收到cookie,返回值是null。
request.getCookies();
  1. 案例:网站实现十天内免登录
    (1)首先在用户登录界面创建复选框,勾选复选框后提交的话浏览器会发送复选框属性name=value的键值对给服务器,服务器用一个if语句判断是否收到这样一个键值对("value").equals(request.getParameter("name")),如果返回true,创建两个cookie对象分别存储用户名和密码,设置cookie失效时间、响应路径,把cookie通过HTTP响应报文传给浏览器保存。
Cookie cookie1 = new Cookie("username",request.getParameter("username"));//创建cookie
Cookie cookie2 = new Cookie("password",request.getParameter("password"));
cookie1.setMaxAge(60*60*24*10);//设置cookie失效时间
cookie2.setMaxAge(60*60*24*10);
cookie1.setPath(request.getContextPath());//设置响应路径
cookie2.setPath(request.getContextPath());
response.addCookie(cookie1);//cookie传给浏览器保存
response.addCookie(cookie2);

(2)创建一个servlet,用于判断是否用户免密登录,用户输入我们网站的URL,有两种可能:1.如果浏览器通过get请求报文传给服务器cookie了,那就说明用户上次点击了免密登录复选框,所以用户的浏览器存有上面的两个cookie,我们只需验证cookie中的用户名密码是否正确即可,正确的话直接让的话用户可以直接转到URL对应的页面。2. 如果浏览器没有发送cookie,服务器没有捕捉到对应的cookie,那不管用户输入了我们webapp的哪个URL,都强制用户跳转到登录页面。

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookies[] = request.getCookies();
        String username = null;
        String password = null;
        if (cookies != null) {//判断浏览器的请求行的cookie字段是否有信息
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())){//获取cookie中的用户名
                    username = cookie.getValue();
                }
                if("password".equals(cookie.getName())){//获取cookie中的密码
                    password = cookie.getValue();
                }
            }
        }
        if(username!=null && password!=null){//用户之前登陆成功且设置了免登录,浏览器保存了cookie
            //验证用户名密码是否正确:为了防止用户点击免登录后改密码
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            boolean flag = false;
            try {
                connection = DButil.getConnection();
                preparedStatement = connection.prepareStatement("select username,password from t_user where username=? and password=?");
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);
                resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {//cookie中的用户名和密码正确
                    flag = true;
                    //获取session,没有则新建
                    HttpSession session = request.getSession();
                    //将用户登录成功的信息存到会话域
                    session.setAttribute("username",username);
                    //重定向,登陆成功后转到list连接数据库获取信息,然后转到list.jsp页面展示
                    response.sendRedirect(request.getContextPath()+"/dept/list");
                }
                if (flag == false) {//cookie中的用户名和密码错误
                    //重定向,密码错误后转到失败页面
                    response.sendRedirect(request.getContextPath()+"/error.jsp");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                DButil.close(connection, preparedStatement, resultSet);
            }
        }else{//用户之前没有登录过,表示该用户第一次访问网站
            //重定向,跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }

    }
}

(3)点击退出按钮删除cookie,session,下次登录需要重新输入用户名密码:

private void doLogout(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        HttpSession session = request.getSession(false);
        if (session != null){
            session.invalidate();//手动销毁session
            //手动销毁cookie
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    cookie.setPath(request.getContextPath());//要删除根路径下的cookie,只删除子路径下的cookie没用
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
            //重定向到登录页面
            response.sendRedirect(request.getContextPath());
        }
    }

(3)将欢迎页由登陆界面改为该servlet,每次用户访问本站将首先执行该servlet判断是否需要登陆:

<!--设置欢迎页主页-->
<welcome-file-list>
    <welcome-file>welcome</welcome-file>
</welcome-file-list>
  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姓蔡小朋友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值