目录
一、会话跟踪技术
1.概述
2.实现方式
3.Cookie
(1)基本使用
(2)原理
(3)存活时间
(4)存储中文
4.Session
(1)基本使用
(2)原理
(3)Session钝化/活化
(4)Session销毁
5.两者区别
6.使用场景
7.登录注册(完善)
(1)记住账号密码:
(2)验证码:
一、会话跟踪技术
1.概述
会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次请求和响应
会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据
原因:HTTP协议是无状态的,每次浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内数据共享
2.实现方式
-
Cookie:客户端会话跟踪技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问
-
Session:服务端会话跟踪技术:将数据保存到服务端
3.Cookie
(1)基本使用
-
发送
-
获取
发送:
-
创建Cookie对象,设置数据
Cookie cookie = new Cookie("key","value");
-
发送Cookie到客户端:使用response对象
response.addCookie(cookie)
谷歌浏览器查看Cookie
f12控制台或右键检查
获取:
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].getName()+":"+cookies[i].getValue());
}
根据需要自行筛选即可
(2)原理
Cookie的实现是基于HTTP协议的
-
响应头:set-cookie
-
请求头:cookie,浏览器自动发送
(3)存活时间
默认情况下,Cookie 存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁
相应的,延长时间方法:
setMaxAge (int seconds):设置Cookie存活时间
-
正数:将 Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除
-
负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁
-
零:删除对应 Cookie
cookie.setMaxAge(60*60*24*7);
(4)存储中文
cookie 不能直接存储中文
-
URL编码:URLEncoder.encode(String s,charset);
4.Session
(1)基本使用
JavaEE 提供 HttpSession接口,来实现一次会话的多次请求间数据共享功能
-
获取Session对象
HttpSession session = request.getSession();
-
Session对象功能
方法名 | 说明 |
---|---|
void setAttribute(String name, Object o) | 存储数据到 session 域中 |
Object getAttribute(String name) | 根据 key,获取值 |
void removeAttribute(String name) | 根据 key,删除该键值对 |
(2)原理
Session是基于Cookie实现的
-
通过请求来获取Session的时候(第一次执行)
-
Session对象会有唯一的标识id
-
存完数据后Tomcat会将Session对象的唯一标识符作为cookie发送给对应的客户端浏览器
-
该浏览器再次请求时,会携带cookie信息进行访问
-
服务器第二次获取Session对象的时候会寻找是否有与cookie中的session一样的唯一标识,如果有就直接拿来用,没有则创建
(3)Session钝化/活化
-
服务器重启后,Session数据是否存在?
-
钝化:在服务器正常关闭后,Tomcat会自动将 Session数据写入硬盘的文件中
-
活化:再次启动服务器后,从文件中加载数据到Session中
-
(4)Session销毁
-
默认情况下,无操作,30分钟自动销毁
如果想要更改,在项目中的web.xml添加配置即可
<web-app>
<session-config>
<!-- 失效时间单位:分钟-->
<session-timeout>100</session-timeout>
</session-config>
</web-app>
-
调用 Session对象的 invalidate()方法
5.两者区别
-
存储位置:
-
Cookie 是将数据存储在客户端
-
Session将数据存储在服务端
-
-
安全性:
-
Cookie 不安全
-
Session安全
-
-
数据大小:
-
Cookie 最大3KB
-
Session 无大小限制
-
-
存储时间:
-
Cookie 可以长期存储
-
Session默认30分钟
-
-
服务器性能:
-
Cookie 不占服务器资源
-
Session 占用服务器资源
-
6.使用场景
-
购物车
-
长期存储
-
-
用户登录数据
-
安全性
-
-
登录(记住账号密码)
-
无法保证安全性
-
-
验证码(防止程序暴力注册)
-
安全性
-
7.登录注册(完善)
-
记住账号密码
-
验证码
简单写了,jsp到这结束,不写了
(1)记住账号密码:
预览图:
先整错误的账号或密码
会弹窗并返回
正确不点记住账号
点击登录并勾上记住账号选项
关闭浏览器,关闭服务器,之后重启
打开登录,会发现账号密码会自动填上
查看cookie数据
jsp页面
还是以前的html,不同的是需要在顶部加三行
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<%-- ${pageContext.request.contextPath} 等价于 /practice02_war--%>
<link rel="stylesheet" href="/practice02_war/jsp/login_register/css/login_and_signing.css" type="text/css">
<script>
var msg = '${loginMsg}';
function info() {
if (msg.length !== 0){
alert(msg)
}
}
info()
</script>
</head>
<body>
<div class="container right-panel-active">
<!-- Sign Up -->
<div class="container__form container--signup">
<form action="/practice02_war/register" class="form" id="form1" method="post">
<h2 class="form__title">注册</h2>
<input type="text" placeholder="User" class="input" name="username" />
<input type="email" placeholder="Email" class="input" name="email"/>
<input type="password" placeholder="Password" class="input" name="password"/>
<button class="btn">注册</button>
</form>
</div>
<!-- Sign In -->
<div class="container__form container--signin">
<form action="/practice02_war/login" class="form" id="form2" method="post">
<h2 class="form__title">登录</h2>
<input type="text" placeholder="用户名/邮箱" class="input" name="voucher" value="${cookie.username.value}"/>
<input type="password" placeholder="Password" class="input" name="password" value="${cookie.password.value}"/>
<input type="checkbox" name="remember" value="1">记住账号
<a href="#" class="link">忘记密码?</a>
<button class="btn">登录</button>
</form>
</div>
<!-- Overlay -->
<div class="container__overlay">
<div class="overlay">
<div class="overlay__panel overlay--left">
<button class="btn" id="signIn">登录</button>
</div>
<div class="overlay__panel overlay--right">
<button class="btn" id="signUp">注册</button>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="${pageContext.request.contextPath}/jsp/login_register/js/login_and_signing.js"></script>
目录结构
Servlet:
Login前面写过,就不放整个代码了
if (user != null){
//成功
HttpSession session = request.getSession();
session.setAttribute("user",user);
//判断是否选择记住账号
if ("1".equals(remember)){
//发送cookie
//创建cookie对象
Cookie cookieUsername = new Cookie("username", user.getUsername());
Cookie cookiePassword = new Cookie("password",user.getPassword());
//设置存活时间
//60*60*24*7 一周
cookieUsername.setMaxAge(60*60*24*7);
cookiePassword.setMaxAge(60*60*24*7);
//发送
response.addCookie(cookieUsername);
response.addCookie(cookiePassword);
}
//跳转,重定向
response.sendRedirect("/practice02_war/selectAll");
}else{
//失败
System.out.println("登录失败了");
//存储错误信息到Request
request.setAttribute("loginMsg","用户名或密码错误");
//跳转
request.getRequestDispatcher("/jsp/login_register/login_and_sigin.jsp").forward(request,response);
}
其他的没变
UserService:
package com.service;
import com.mapper.UserMapper;
import com.pojo.User;
import com.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class UserService {
final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
public String selectByName(String username){
final SqlSession sqlSession = sqlSessionFactory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final String name = mapper.selectByUsername(username);
sqlSession.close();
return name;
}
public String selectByEmail(String email){
final SqlSession sqlSession = sqlSessionFactory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final String e = mapper.selectByEmail(email);
sqlSession.close();
return e;
}
public User selectInfoByUP(String username, String password){
final SqlSession sqlSession = sqlSessionFactory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final User user = mapper.selectInfoBy_U_P(username, password);
sqlSession.close();
return user;
}
public User selectInfoByEP(String email, String password){
final SqlSession sqlSession = sqlSessionFactory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final User user = mapper.selectInfoBy_E_P(email, password);
sqlSession.close();
return user;
}
public void addUser(String username,String email,String password){
final SqlSession sqlSession = sqlSessionFactory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.add(username,email, password);
sqlSession.commit();
sqlSession.close();
}
}
(2)验证码:
感兴趣可以自己写写看,想省事的可以直接用写好的~
工具类(粘的):
package com.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* 生成验证码工具类
*/
public class CheckCodeUtil {
public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
*
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 使用系统默认字符源生成验证码
*
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
*
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources) {
// 未设定展示源的字码,赋默认值大写字母+数字
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
*
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
*
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
//文件不存在
if (!dir.exists()) {
//创建
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}
/**
* 输出指定验证码图片流
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建颜色集合,使用java.awt包下的类
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
// 设置边框色
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
// 设置背景色
g2.setColor(c);
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
// 设置线条的颜色
g2.setColor(getRandColor(160, 200));
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
// 噪声率
float yawpRate = 0.05f;
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
// 获取随机颜色
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
// 添加图片扭曲
shear(g2, w, h, c);
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
/**
* 随机颜色
*
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
简单测试:
public class Demo {
public static void main(String[] args) throws IOException {
OutputStream fos = new FileOutputStream("E://a.jpg");
//宽,高,输出流,验证码长度(记得调整宽高)
final String s = CheckCodeUtil.outputVerifyImage(100, 50, fos, 12);
System.out.println(s);
}
}
其他验证码工具类:
Java生产验证码各种工具类_arithmeticcaptcha-CSDN博客
jsp页面,只改部分,看出效果即可:
<form action="/practice02_war/register" class="form" id="form1" method="post">
<h2 class="form__title">注册</h2>
<input type="text" placeholder="User" class="input" name="username" />
<input type="email" placeholder="Email" class="input" name="email"/>
<input type="password" placeholder="Password" class="input" name="password"/>
<input type="text" class="input" id="checkCodeInput" placeholder="请输入验证码" name="check">
<div class="checkBox">
<img id="checkCode" class="input" src="/practice02_war/checkCode" style="width: 100px;height: 50px">
<a href="" id="change">看不清?</a>
</div>
<button class="btn">注册</button>
</form>
css样式修改一下:
.checkBox {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
width: 100%;
height: 75px;
}
.checkBox a {
display: block;
}
Servlet
checkCode
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//生成验证码
final ServletOutputStream outputStream = response.getOutputStream();
//宽,高,输出流,验证码长度(记得调整宽高)
final String s = CheckCodeUtil.outputVerifyImage(100, 50, outputStream, 4);
//保存验证码
final HttpSession session = request.getSession();
session.setAttribute("checkCode",s);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
register:
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String username = request.getParameter("username");
final String email = request.getParameter("email");
final String password = request.getParameter("password");
final String check = request.getParameter("check");
response.setContentType("text/html;charset=utf-8");
UserService userService = new UserService();
final HttpSession session = request.getSession();
final String code = (String)session.getAttribute("checkCode");
if (userService.selectByName(username) != null){
//存储错误信息到Request
request.setAttribute("Msg","注册失败:用户名已存在");
//跳转
request.getRequestDispatcher("/jsp/login_register/login_and_sigin.jsp").forward(request,response);
}else if (userService.selectByEmail(email) != null){
//存储错误信息到Request
request.setAttribute("Msg","注册失败:邮箱已使用");
//跳转
request.getRequestDispatcher("/jsp/login_register/login_and_sigin.jsp").forward(request,response);
}else {
if (code.equalsIgnoreCase(check)){
userService.addUser(username, email, password);
//存储信息到Request
request.setAttribute("Msg","注册成功");
//跳转
request.getRequestDispatcher("/jsp/login_register/login_and_sigin.jsp").forward(request,response);
}else {
//存储信息到Request
request.setAttribute("Msg","验证码错误");
//跳转
request.getRequestDispatcher("/jsp/login_register/login_and_sigin.jsp").forward(request,response);
}
}
}
预览:表格大小根据需要自己调吧
测试结果写完自己看,还有就是这代码没有输入内容是否为空的判断,注意一下