会话技术客户端Cookie和服务器端Session

1 客户端Cookie

客户端Cookie工作原理

会话技术客户端Cookie和服务器端Session_druid

//ServletCookie_01.class中
// 1 创建cookie
Cookie cookie = new Cookie("name", "beijing");
// 2 发送cookie
response.addCookie(cookie);

//ServletCookie_02.class中
// 3 接受cookie
Cookie[] cookies = request.getCookies();
// 4 遍历coolie的值
if (cookies != null) {
for (Cookie c : cookies
) {
String name = c.getName();
String value = c.getValue();
System.out.println(name + ":" + value);
}
}


1、Cookie可以创建多个对象,发送多个cookie
2、一般情况,当浏览器关闭时,cookie数据被清理


cookie数据持久化:

// 1    创建cookie
Cookie cookie = new Cookie("name", "beijing");
// 2 设置cookie存活时间
cookie.setMaxAge(30);//将cookie持久化到硬盘,30s后自动删除cookie文件
cookie.setMaxAge(-1);//默认值
cookie.setMaxAge(0);//删除cookie的值
// 发送cookie
response.addCookie(cookie);

案例:浏览器记住上一次访问时间

1.需求:

访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您首次访问。

如果不是第一次访问,则提示:欢迎回来,您上次访问时间为:显示时间字符串

2.分析:

1.可以采用cookile来完成
2.在服务器中的Servlet判断是否有一个名为lastTime的cookie

有:不是第一次访问

响应数据:欢迎回来,您上次访问时间为:

写回cookie : lastTime=

没有:是第一次访问

响应数据:您好,欢迎您首次访问

写回Cookie : lastTime=

package Cookie;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "ServletCookie_04", value = "/ServletCookie_04")
public class ServletCookie_04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应的消息体的数据格式和编码方式
response.setContentType("text/html;charset=utf-8");
// 1 获取所有cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lastTime
if (cookies == null || cookies.length == 0 || flag == false) {
// 没有,第一次访问
//设置cookie的value
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = simpleDateFormat.format(date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
//设置value的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
response.getWriter().write("您好,欢迎首次访问!");
}
// 2 遍历cookie的名称
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies
) {
// 3 获取cookie名称
String name = cookie.getName();
// 4 判断名称是否是:lastTime
if ("lastTime".equals(name)) {
// 有cookie为lastTime,不是第一次访问
flag = true;
//响应数据
//获取cookie的value,时间
String value = cookie.getValue();
//URL解码
value = URLDecoder.decode(value, "utf-8");
response.getWriter().write("欢迎回来,您上次访问时间为:" + value);
//更新value,将本次访问时间存到value
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = simpleDateFormat.format(date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
//设置value的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
break;
}
}
}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

该案例使用jsp代码展示为:

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%--
Created by IntelliJ IDEA.
User:
Date:
Time: 20:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ShowTime</title>
</head>
<body>
<%
// 1 获取所有cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lastTime
if (cookies == null || cookies.length == 0 || flag == false) {
// 没有,第一次访问
//设置cookie的value
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = simpleDateFormat.format(date);
// //URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
//设置value的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
out.write("您好,欢迎首次访问!");
}
// 2 遍历cookie的名称
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies
) {
// 3 获取cookie名称
String name = cookie.getName();
// 4 判断名称是否是:lastTime
if ("lastTime".equals(name)) {
// 有cookie为lastTime,不是第一次访问
flag = true;
//响应数据
//获取cookie的value,时间
String value = cookie.getValue();
//URL解码
value = URLDecoder.decode(value, "utf-8");
out.write("欢迎回来,您上次访问时间为:" + value);
//更新value,将本次访问时间存到value
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = simpleDateFormat.format(date);
//URL编码
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
//设置value的存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
break;
}
}
}
%>
</body>
</html>

2 服务器端Session

1、获取session对象

2、使用session对象

//ServletSession_01.java
// 使用session共享数据
// 1 获取session
HttpSession session = request.getSession();
// 2 存储数据
session.setAttribute("name","beijing");

//ServletSession_02.java
// 使用session获取数据
HttpSession session = request.getSession();
Object name = session.getAttribute("name");
System.out.println(name);


当客户端关闭时,服务器不关闭,再次获取的session不一样


期望客户端关闭后,session也能相同:

// 1    获取session
HttpSession session = request.getSession();
//期望客户端关闭后,session也能相同
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);

案例:验证码验证登录

需求:
1.访问带有验证码的登领面login. jsp
2.用户输入用户名,密码以及验证码。
如果用户名和密码输入有误,跳转登录页面,提示:用户名或密码错误
如果验证码输入有误,跳转登录页面,提示:验证码错误
如果全部输入正确,则跳转到主页success.jsp,显示:用户名,欢迎您

该案例是基于前面文章中一个登录案例:地址:​​用户登录​​​ 和一个验证码案例:地址:​​验证码​​,综合以上两个案例进行升级改造的。

分析:
1、设置request的编码
2、获取用户名、密码、验证码参数集合
3、获取验证码
4、将用户信息封装到User对象
5、判断程序的生成的验证码和用户输入的验证码是否一致。
从session中获取程序生成的验证码。
不一致:
1、提示信息:验证码错误 request
2、跳转登录页面 转发
一致:
再判断用户名和密码是否正确(查询数据库)
正确:
登录成功;
存储数据 session
跳转到success.jsp 重定向
不正确:
1、给提示信息
2、跳转到登录页面

1、创建用户实体类User.java,用于封装数据:

package User;

public class User {
private int id;
private String username;
private String password;
private String checkCode;


public void setId(int id) {
this.id = id;
}

public void setUsername(String username) {
this.username = username;
}

public void setPassword(String password) {
this.password = password;
}

public void setCheckCode(String checkCode) {
this.checkCode = checkCode;
}

public int getId() {
return id;
}

public String getUsername() {
return username;
}

public String getPassword() {
return password;
}

public String getCheckCode() {
return checkCode;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", check='" + checkCode + '\'' +
'}';
}
}

2、创建验证码生成类Servlet_yanzhengma.java:

package Servlet;

import javax.imageio.ImageIO;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "Servlet_yanzhengma", value = "/Servlet_yanzhengma")
public class Servlet_yanzhengma extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.创建一对象,在内存中图片(验证码图片对象)
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化图片
//2.1 填充背景色
Graphics graphics = bufferedImage.getGraphics();//画笔对象
graphics.setColor(Color.PINK);
graphics.fillRect(0, 0, width, height);
//2.2 画边框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);
//2.3写验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxqz0123456789";
//生成随机角标
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = random.nextInt(str.length());
//获取字符
char c = str.charAt(index);
stringBuilder.append(c);
//2.3 写验证码
graphics.drawString(c + "", width / 5 * i, height / 2);
}
String CheckCode_session = stringBuilder.toString();
//将验证码存入session
request.getSession().setAttribute("CheckCode_session",CheckCode_session);
//2.4画干扰线
graphics.setColor(Color.GREEN);
//随机生成坐标点
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
//3.将图片输出到页面展示
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

因为后面需要首先验证用户输入的验证码是否成功,所以在设置验证码代码里加入下面三行代码,将动态生成的验证码存入到session中,后续取出进行验证码验证。

会话技术客户端Cookie和服务器端Session_开发语言_02

3、创建登录表单页面login.jsp(使用jsp),包含三个表单和一个验证码图片,验证码添加onclick事件,实现验证码动态刷新:

<%--
Created by IntelliJ IDEA.
User: LINUX
Date: 2022/3/2
Time: 16:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
<script>
window.onload = function () {
document.getElementById("img").onclick = function () {
this.src = "/LogIn2_war_exploded/Servlet_yanzhengma?" + new Date().getTime();
}
}

</script>
<style>
div {
color: red;
}
</style>
</head>
<body>
<form action="/LogIn2_war_exploded/loginServlet" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="checkCode"></td>
</tr>
<tr>
<td colspan="3"><img id="img" src="/LogIn2_war_exploded/Servlet_yanzhengma"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="登录"></td>
</tr>
</table>

<div><%=request.getAttribute("check_error") == null ? "" : request.getAttribute("check_error")%>
</div>
<div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error")%>
</div>
</form>
</body>
</html>

在最后使用三元表达式输出:当验证码错误时提示验证码错误,用户名和密码错误时提示用户名和密码错误。

会话技术客户端Cookie和服务器端Session_druid_03

4、创建loginServlet.java,实现主要的业务逻辑,获取jsp表单参数,使用使用BeanUtils封装对象,使用Druid和jdbcTemplate来调取MySQL数据库中用户名和密码就行登录验证;这里使用到前面登录案例的工具类:

会话技术客户端Cookie和服务器端Session_开发语言_04

会话技术客户端Cookie和服务器端Session_后端_05

会话技术客户端Cookie和服务器端Session_druid_06

会话技术客户端Cookie和服务器端Session_后端_07

package Servlet;

import Dao.UserDao;
import User.User;
import org.apache.commons.beanutils.BeanUtils;


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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、设置编码
request.setCharacterEncoding("utf-8");
// 2、获取表单参数
Map<String, String[]> parameterMap = request.getParameterMap();
User user = new User();
try {
// 使用BeanUtils封装对象
BeanUtils.populate(user, parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 3、获取生成的验证码
String checkCode_session = (String) request.getSession().getAttribute("CheckCode_session");
// 删除session中存储的验证码
request.getSession().removeAttribute("checkCode_session");
// 4、先判断验证码是否相同
if (checkCode_session != null && checkCode_session.equalsIgnoreCase(user.getCheckCode())) {
//验证码一致
//忽略大小写比较
//判断用户名和密码是否一致
//调用UserDao类使用其登录方法
UserDao userDao = new UserDao();
User login = userDao.login(user);
if (login != null) {//有返回值,说明用户名和密码验证成功
//存储用户信息
request.getSession().setAttribute("user", user.getUsername());
//重定向到成功页面
response.sendRedirect(request.getContextPath() + "/success.jsp");
} else {//登录失败
//存储信息
request.setAttribute("login_error", "用户名和密码错误");
//转发到登录首页
request.getRequestDispatcher("LogIn.jsp").forward(request, response);
}
} else {
//验证码不一致
//存储信息到request
request.setAttribute("check_error", "验证码错误");
//转发到登录页面
request.getRequestDispatcher("LogIn.jsp").forward(request, response);
}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

5、创建登录成功页面success.jsp,使用session对象获取session中的用户名信息并展示。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h2><%=request.getSession().getAttribute("user")%>,欢迎您!!</h2>
</body>
</html>