文章目录
前言
提示:这里可以添加本文要记录的大概内容:
提示:以下是本篇文章正文内容,下面案例可供参考
一、Cookie
1:Cookie是什么?
Cookie:是浏览器在本地持久化存储数据的一种机制。
2:Cookie的数据从哪来?
Cookie的数据是浏览器返回给浏览器的。
3:Cookie的数据长啥样 ?
Cookie中是键值对中的数据,并且这些键值对中的数据都是程序员自定义的。
4:Cookie的作用
5:Cookie到哪里去?
Cookie中的内容会在下次访问该网站的时候,自动被带到http请求中。
6:Cookie怎么存的?
浏览器按照不同的"域名"分别存储cookie.域名和域名之间的cookie是不同的。
Cookie是存储在硬盘上。Cookie往往会有超时时间。
二.代码
我在springboot中写的代码
package com.example.demo.demos.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@Controller
public class MyController {
@RequestMapping ("/getCookies")
@ResponseBody
public String getCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println("Cookie Name: " + cookie.getName());
System.out.println("Cookie Value: " + cookie.getValue());
}
} else {
System.out.println("No cookies found");
}
// 这里可以返回视图或其他逻辑
return "cookieView";
}
}
刚打开8080的窗口肯定是没有cookie的
打开f12
我们自己加一个cookie的值,然后刷新
三、Session
package com.example.demo.demos.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
// 显示登录页面
@RequestMapping("/login")
@ResponseBody
public String showLoginPage() {
return "login";
}
// 处理登录请求
@RequestMapping("/login2")
@ResponseBody
public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) {
if (username == null || password == null || username.equals("") || password.equals("")) {
model.addAttribute("message", "当前请求参数不完整");
return "login";
}
// 验证用户名和密码是否正确,这里简单模拟一个合法用户
if (!username.equals("zhangsan") || !password.equals("123")) {
model.addAttribute("message", "当前用户名或密码错误");
return "login";
}
// 登录成功,创建session
session.setAttribute("username", username);
session.setAttribute("time", System.currentTimeMillis());
// 重定向到index页面
return "redirect:/index";
}
// 显示首页
// 显示首页
@RequestMapping("/index")
@ResponseBody
public String showIndexPage(HttpSession session, Model model) {
// 在index页面显示用户名信息
String username = (String) session.getAttribute("username");
Long time = (Long) session.getAttribute("time");
// 如果用户名或时间戳为null,执行相应的处理逻辑
if (username == null || time == null) {
return "User information not available";
}
// 打印用户名和时间戳到控制台
System.out.println("用户名: " + username + " 时间戳: " + time);
// 返回一个字符串作为响应
return "Welcome, " + username + "!";
}
}
总结
好了,博客到这里结束