【什么是 cookie】
Cookie 是服务器端通知客户端保存键值对的一种技术。
Cookie 是 servlet (服务器)发送到 Web 浏览器(客户端)的少量信息,这些信息由浏览器保存,然后发送回服务器。
客户端有了 Cookie 后,每次请求都会发送 Cookie 给服务器。
每个 Cookie 的大小不能超过 4KB。
cookieTest1
package Test;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/cook1")
public class Cooke1test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一个名字为name的cookie
Cookie namecookie = new Cookie("name", "lzh");
// 设置cookie的过期时间(以秒为单位)
namecookie.setMaxAge(10);
//发送cookie给客户端
resp.addCookie(namecookie);
}
}
cookieTest2
package Test;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/cook2")
public class Cooke2test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
if (cookies !=null){
System.out.println("111 = " + 111);
for (Cookie cookie:cookies){
String name = cookie.getName();
System.out.println("name = " + name);
String value = cookie.getValue();
System.out.println("value = " + value);
}
}
}
}
【什么是 Session 对话】
Session 是一个 Java 中的接口(HttpSession)。
Session 就是会话,用来维护一个客户端和服务器之间关联的一种技术。
每个客户端都有一个自己的 Session 会话。
Session 会话中,我们经常用来保存用户登录后的信息,前面的 Cookie 是保存在客户端,而 Session 是保存在服务器端。
2、Session 的创建和获取
(1)创建和获取 Session,都是通过 request.getSession() 来实现的。
第一次调用:创建 Session 对象;
之后的调用:获取之前创建好的 Session 会话对象。
(2)可以用 isNew() 方法来判断一个 Session 是不是刚创建出来的。
true:表示刚创建
false:表示获取之前创建
(3)每个会话都有一个身份证号,也就是 ID 值,且这个 ID 唯一。
getId() 方法获取 Session 对象的 ID 值
sessionTest1
package Test;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/arequest1")
public class Session1test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 开启会话,创建一个会话对象session
HttpSession session = req.getSession();
//会话管理中心设置数据 键:值 对
session.setAttribute("ok", "学习java");
session.setAttribute("ok1", "学习php");
//获取设置的值,当前页面
System.out.println("session.getAttribute(\"ok\") = " + session.getAttribute("ok"));
System.out.println("session.getAttribute(\"ok1\") = " + session.getAttribute("ok1"));
}
}
sessionTest2
package Test;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/arequest2")
public class Session2test extends GenericServlet {
//继承接口 GenericServlet ,抽象类,实现抽象方法就好
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
// 开启会话,向下转型
HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
HttpSession session = servletRequest1.getSession();
String ok = (String)session.getAttribute("ok");
String ok1 = (String)session.getAttribute("ok1");
System.out.println("ok = " + ok);
System.out.println("ok1 = " + ok1);
}
}
sessionTest3
package Test;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/arequest3")
public class Session3test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String ok =(String) session.getAttribute("ok");
// Object ok1 = session.getAttribute("ok1");
String ok1 = (String)session.getAttribute("ok1");
// 将session转换成字符串类型进行输出,object类型无法输出
System.out.println("ok = " + ok);
System.out.println("ok1 = " + ok1);
}
}
【代码案例】
/*-------------
代码片段1
------------------------------*/
packagexdp.gacl.session;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
publicclass SessionDemo1 extends HttpServlet {
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setCharacterEncoding("UTF=8");
response.setContentType("text/html;charset=UTF-8");
//使用request对象的getSession()获取session,如果session不存在则创建一个
HttpSessionsession = request.getSession();
//将数据存储到session中
session.setAttribute("data","孤傲苍狼");
//获取session的Id
StringsessionId = session.getId();
//判断session是不是新创建的
if(session.isNew()) {
response.getWriter().print("session创建成功,session的id是:"+sessionId);
}else {
response.getWriter().print("服务器已经存在该session了,session的id是:"+sessionId);
}
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
doGet(request,response);
}
}
HttpSessionsession = request.getSession();
//手工调用session.invalidate方法,摧毁session
session.invalidate()
/*-------------
代码片段2
------------------------------*/
// 创建一个名为 "username" 的 Cookie
CookieusernameCookie = new Cookie("username", "john_doe");
// 设置 Cookie 的过期时间(以秒为单位)
usernameCookie.setMaxAge(3600);// 1 小时
// 设置 Cookie 的路径
usernameCookie.setPath("/");
// 发送 Cookie 给客户端
response.addCookie(usernameCookie);
Cookie[]cookies = request.getCookies();//读取Cookie
if(cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
// 处理 Cookie 数据
}
}
【登陆小案例】
//HomePageServlet.java
/*当用户访问homepage.jsp时,判断请求中是否携带username的Cookie,如果不存在就通知浏览器跳转到登录页面进行用户信息的登记。当用户再次访问homepae.jsp时,不会被拦截,可以让用户访问个人主页页面。*/
@WebServlet(name = "homepageServlet", urlPatterns = "/homepage")
public class HomePageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (!cookie.getName().equals("username")) {
// 如果用户是第一次访问个人主页,就通知浏览器跳转到登陆页面进行登录
resp.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
}
}
// LoginServlet.java
@WebServlet(name = "loginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取http请求参数username
String username = request.getParameter("username");
// 设置响应内容的类型
response.setContentType("text/html;charset=utf-8");
// 获取Cookie值
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (!cookie.getName().equals("username")) { // 用户第一次访问
Cookie userCookie = new Cookie("username", username);
userCookie.setMaxAge(300);
response.addCookie(userCookie);
}
response.sendRedirect(request.getContextPath() + "/homepage.jsp");
}
}
}
在第一次访问homepage页面时,看到浏览器缓存区并没有名为username的Cookie,只有当登录之后,浏览器缓存区才有了这个Cookie。
【查阅资料】
[Java | Web] JavaWeb——Cookie 和 Session 简介_javaweb session存取-CSDN博客 (非常详细)
Cookie在Java中的使用_java_脚本之家