10分钟学习Cookie+Session机制,实现用户登录功能

Cookie+Session机制,实现用户登录功能

首先先来看看Cookies的运行机制,代码如下:

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;

public class SetcookiesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        Cookie usernameCookie = new Cookie("username","java");
        //设置Cookie的生命周期
        usernameCookie.setMaxAge(60);
        //告诉用户存储C哦OkIE信
        response.addCookie(usernameCookie);


        //告诉用户cookies被保存了
        PrintWriter writer = response.getWriter();
        writer.println("<h1>Cookie保存成功!</h1>");
    }
}

下面是Session的运行机制,代码如下:



import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     this.doGet(request,response);
    }
//session和Cookie的区别
    /*
    * 1.session和cookie的存储机制是不一样的,cookie是浏览器端实现的会话保持,而sessions是服务器中实现的对话
    * 2.session是没有内存限制的,而cookie是有存储限制的,一般是4K
    * 3.session安全性高(每次访问都有一个密钥,也就是session id),不能被篡改,而cookie信息是会被长篡改的
    * */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        PrintWriter writer = response.getWriter();
        if(name!=null && pwd!=null&&name.equals("root")&& pwd.equals("root")){
            HttpSession session = request.getSession();
            String sessionId = session.getId();
            writer.println("<h1>欢迎登录<h1>");
            writer.println(String.format("<h3>ID;%s</h3>",sessionId));

        }else{

            writer.println();
        }
    }
}

利用 cookies 登录代码如下:

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;

public class GetcookiesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        //得到Cookie
        request.getCookies();
        Cookie[] cookies = request.getCookies();
        PrintWriter writer = response.getWriter();
        for(Cookie cookie : cookies){
            writer.println(String.format("<h1>Cookie name:%s,Cookie value:%s</h1>",cookie.getName(),cookie.getValue()));
        }
    }
}

利用Session机制登录,代码如下

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

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        String username = request.getParameter("number1");
        String pwd = request.getParameter("number2");
        PrintWriter writer = response.getWriter();
       if(username.equals("admin")&& pwd.equals("admin")){
           writer.println(String.format("<p>登录成功!</p>"));
       }else{
           writer.println(String.format("<p>用户名或密码错误!请重新登录</p>"));
       }

    }
}

创建一个登录页面,利用Cookie+Session机制,实现用户登录功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <style>
        body{
          background-image: url("https://qqpublic.qpic.cn/qq_public/0/0-2732045526-67C005C93544B8D957A49EDB0C590309/900");
        }
        .text{
            color: #f0f8ff;
        }
    </style>
    <script>
        function myck(type) {
             const username = document.getElementById("n1");
             const pwd = document.getElementById("n2");
             if(type==1){
                 if(username.value==''||pwd.value==''){
                     alert("用户名或密码没有填写");
                     return false;
                 }
             }

             if(type==2){
                 if(confirm("确认清除?")){
                     username.value='';
                     pwd.value='';
                 }
             }
        }
    </script>>
</head>
<body>
<form method="post" action="login">
    <div class="text" style="text-align: center;margin-top: 325px;">
        <h2>管理员登录</h2>
        用户名:<input id="n1" name="number1" type="text"><p></p>
        密&nbsp&nbsp&nbsp码:<input id="n2" name="number2" type="text"><p></p>
        <input value=" 提 交 " type="submit" onclick="myck(1)">
        <input value=" 清 除 " type="button" onclick="myck(2)">

    </div>
</form>
</body>
</html>

运行截图如下:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

沉默着忍受

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

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

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

打赏作者

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

抵扣说明:

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

余额充值