会话

用户打开浏览器、访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次请求和响应。

会话跟踪

一种维护浏览器状态的方法、服务器需要识别多次请求是否来自于同一浏览器,以便在同一次会话的多次请求间共享数据
HTTP协议是无状态的,每次浏览器向服务器发送请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内的数据共享

实现方式

客户端会话跟踪技术:Cookie
服务器端会话跟踪技术:Session

Cookie

执行流程:

1.客户端会向服务器端发送一个http请求

2.服务器端在接收请求之后,会发送一个http响应到客户端,这个响应头,其中就包含set-Cookie头部,接着浏览器保存cookie

3.浏览器第二次访问服务器,将保存的cookie发送给服务器,服务器识别并且更新cookie,返回给浏览器并再次保存

java 跟踪技术 javaweb会话跟踪技术有哪些_sql


java 跟踪技术 javaweb会话跟踪技术有哪些_servlet_02

//创建cookie
Cookie cookie1=new Cookie("username",username);
Cookie cookie2=new Cookie("password",password);
//设置cookie存活时间(一星期)
cookie1.setMaxAge(60*60*24*7);
cookie2.setMaxAge(60*60*24*7);

//发送cookie到客户端
resp.addCookie(cookie1);
resp.addCookie(cookie2);

//在jsp页面中cookie取值
${cookie.username.value}
${cookie.password.value}

Session

Session是基于Cookie实现的

执行流程:

1.浏览器端第一次发送请求到服务器端,服务器端创建一个Session,同时会创建一个特殊的Cookie(name为JSESSIONID的固定值,value为session对象的ID),然后将该Cookie发送至浏览器端

2.浏览器端发送第N(N>1)次请求到服务器端,浏览器端访问服务器端时就会携带该name为JSESSIONID的Cookie对象

3.服务器端根据name为JSESSIONID的Cookie的value(sessionId),去查询Session对象,从而区分不同用户。

java 跟踪技术 javaweb会话跟踪技术有哪些_sql_03


java 跟踪技术 javaweb会话跟踪技术有哪些_学习_04

//在发送和接收session之前都要先创建session对象
HttpSession session=req.getSession();
//存储数据
session.setAttribute("username",username);
//获取session数据
session.getAttribute("username");

案例:登录注册案例(Cookie与Session的使用)

java 跟踪技术 javaweb会话跟踪技术有哪些_java 跟踪技术_05


部分实现代码:

UserService
package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    //获取sqlSessionFactory对象
    private SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();

    public User select(String username,String password)
    {
        //获取sqlSession对象
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //获取mapper接口的代理
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //调用selectByName()方法
        User user=userMapper.select(username,password);

        //释放资源
        sqlSession.close();

        return user;
    }

    //用户注册
    public boolean register(User user)
    {
        //获取sqlSession对象
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //获取mapper接口的代理
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //调用selectByName()方法
        User user1=userMapper.selectByUsername(user.getUsername());
        if(user1==null)
        {
            //用户名不存在,则进行注册
            userMapper.add(user);
            //提交事务
            sqlSession.commit();

        }
        //释放资源
        sqlSession.close();

        //user1==null则返回true,否则,返回false,这样写简化了返回操作
        return user1==null;
    }
}
loginServlet
package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService=new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       //获取用户输入的用户名和密码
        String username=req.getParameter("username");
        String password=req.getParameter("password");

        //获取复选框数据
        String remember=req.getParameter("remember");

        //将数据封装到user对象中
        User user1=new User();
        user1.setUsername(username);
        user1.setPassword(password);

        //调用UserService的login方法
        User user=userService.select(username,password);
        HttpSession session=req.getSession();
        if(user !=null)
        {
            //登录成功

            //获取Session对象
            session.setAttribute("username",username);
            //用户选中记住我
            if("1".equals(remember))
            {
                //发送Cookie,将用户名密码存入cookie中,用于浏览器长期存储
                Cookie cookie1=new Cookie("username",username);
                Cookie cookie2=new Cookie("password",password);

                //设置cookie存活时间(一星期)
                cookie1.setMaxAge(60*60*24*7);
                cookie2.setMaxAge(60*60*24*7);

                //发送cookie到客户端
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }

            //无数据共享,使用重定向跳转
            String contenxPath=req.getContextPath();
            resp.sendRedirect(contenxPath+"/selectAllServlet");
        }
        else
        {
            //登录失败
            String msg="用户名或密码错误";
            session.setAttribute("msg",msg);

            //无数据共享,使用重定向跳转
            String contenxPath=req.getContextPath();
            resp.sendRedirect(contenxPath+"/login.jsp");

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
registerServlet
package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    private UserService userService=new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取用户名和密码
        String username=req.getParameter("username");
        String password=req.getParameter("password");


        //将数据封装到user对象中
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        //获取用户输入的验证码
       String user_code=req.getParameter("checkCode");
       //获取程序生成的验证码
        HttpSession session=req.getSession();
        String pro_code=(String) session.getAttribute("checkcodevalue");

        //校验验证码(忽略大小写进行比较)
        if(!pro_code.equalsIgnoreCase(user_code))
        {
            //比对不一样,则不允许注册
            req.setAttribute("code_err","验证码错误,请重新输入");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }


        //调用Userservice的register方法
        boolean flag=userService.register(user);
        //判断注册成功与否
        if(flag)
        {
            //注册成功,跳转到登录页面
            req.setAttribute("register_msg","注册成功,请登录");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);

        }
        else
        {
            //注册失败,跳转到注册页面
            req.setAttribute("register_err","用户名已经存在");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link href="css/login.css" rel="stylesheet">
</head>

<body>
<div id="loginDiv" style="height: 350px">
    <form action="/brand-demo/loginServlet" id="form" method="post">
        <h1 id="loginMsg">LOGIN IN</h1>
        <div id="errorMsg" >${msg} ${register_msg}</div>
        <p>Username:<input id="username" name="username" type="text" value="${cookie.username.value}"></p>

        <p>Password:<input id="password" name="password" type="password" value="${cookie.password.value}"></p>
        <p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
        <div id="subDiv">
            <input type="submit" class="button" value="login up">
            <input type="reset" class="button" value="reset">   
            <a href="/brand-demo/register.jsp">没有账号?</a>
        </div>
    </form>
</div>

</body>
</html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎注册</title>
    <link href="css/register.css" rel="stylesheet">
</head>
<body>

<div class="form-div">
    <div class="reg-content">
        <h1>欢迎注册</h1>
        <span>已有帐号?</span> <a href="/brand-demo/login.jsp">登录</a>
    </div>
    <form id="reg-form" action="/brand-demo/registerServlet" method="post">

        <table>

            <tr>
                <td>用户名</td>
                <td class="inputs">
                    <input name="username" type="text" id="username">
                    <br>
                    <span id="username_err" class="err_msg">${register_msg} ${code_err}</span>
                </td>

            </tr>

            <tr>
                <td>密码</td>
                <td class="inputs">
                    <input name="password" type="password" id="password">
                    <br>
                    <span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
                </td>
            </tr>


            <tr>
                <td>验证码</td>
                <td class="inputs">
                    <input name="checkCode" type="text" id="checkCode">
                    <img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
                    <a href="#" id="changeImg">看不清?</a>
                </td>
            </tr>

        </table>

        <div class="buttons">
            <input value="注 册" type="submit" id="reg_btn">
        </div>
        <br class="clear">
    </form>

</div>

<%--验证码看不清问题--%>
<script>
    // 当用户点击看不清验证码图片的时候,会再次请求生成一张验证码
    document.getElementById("changeImg").onclick=function ()
    {
        document.getElementById("checkCodeImg").src="/brand-demo/checkCodeServlet?"+new Date().getMilliseconds();
    }
</script>
</body>
</html>

校验验证码

CheckCodeUtil
package com.itheima.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);
            }

        }

    }
}
CheckCodeServlet
package com.itheima.web;

import com.itheima.util.CheckCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成验证码图片
        ServletOutputStream os=resp.getOutputStream();
        //调用checkcodeutil工具类的outputVerifyImage()方法
        //生成验证码图片并返回生成验证码图片中的字符串
        String checkcode= CheckCodeUtil.outputVerifyImage(100,50,os,4);

        //验证码校验
        //存入session
        HttpSession session=req.getSession();
        //将验证码存入session中
        session.setAttribute("checkcodevalue",checkcode);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
在前端实现的代码
<td>验证码</td>
                <td class="inputs">
                    <input name="checkCode" type="text" id="checkCode">
                    <img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
                    <a href="#" id="changeImg">看不清?</a>
                </td>
            </tr>

        </table>

        <div class="buttons">
            <input value="注 册" type="submit" id="reg_btn">
        </div>
        <br class="clear">
    </form>

</div>

<%--验证码看不清问题--%>
<script>
    // 当用户点击看不清验证码的时候,会再次请求生成一张验证码
    document.getElementById("changeImg").onclick=function ()
    {
        document.getElementById("checkCodeImg").src="/brand-demo/checkCodeServlet?"+new Date().getMilliseconds();
    }
</script>
校验
//获取用户输入的验证码
       String user_code=req.getParameter("checkCode");
       //获取程序生成的验证码
        HttpSession session=req.getSession();
        String pro_code=(String) session.getAttribute("checkcodevalue");

        //校验验证码(忽略大小写进行比较)
        if(!pro_code.equalsIgnoreCase(user_code))
        {
            //比对不一样,则不允许注册
            req.setAttribute("code_err","验证码错误,请重新输入");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }