小黑子—JavaWeb:第五章 - JSP与会话跟踪技术

JavaWeb入门5.0

  • 1. JSP
    • 1.1 JSP快速入门
    • 1.2 JSP原理
    • 1.3 JSP脚本
      • 1.3.1 JSP缺点
    • 1.4 EL 表达式
    • 1.5 JSTL 标签
      • 1.5.1 JSTL 快速入门
        • 1.5.1 - I JSTL标签if
        • 1.5.1 - II JSTL标签forEach
    • 1.6 MVC模式
    • 1.7 三层架构
    • 1.8 实现案例
      • 1.8.1 环境准备
      • 1.8.2 查询所有
      • 1.8.3 添加数据
      • 1.8.4 修改
        • 1.8.4 - I 修改回显数据
        • 1.8.4 - II 修改数据
  • 2. 会话跟踪技术
    • 2.1 Cookie
      • 2.1.1 Cookie基本使用
      • 2.1.2 Cookie原理
      • 2.1.3 Cookie使用细节
    • 2.2 Session
      • 2.2.1 Session基本使用
      • 2.2.2 Session原理
      • 2.2.3 Session使用细节
    • 2.3 小结
    • 2.4 案例
      • 2.4.1 用户登录
      • 2.4.2 记住用户
        • 2.4.2 - I 写cookie
        • 2.4.2 - II 获取cookie
      • 2.4.3 用户注册
      • 2.4.4 验证码
        • 2.4.4 - I 校验验证码

1. JSP

概念:Java Server Pags,java服务端页面

  • 一种动态的网页接收,其中即可以定义HTML、JS、CSS等静态内容,还可以定义Java代码的动态内容
  • JSP = HTML + Java
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第1张图片

1.1 JSP快速入门

  1. 导入JSP坐标
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2version>
      <scope>providedscope>
    dependency>
  1. 创建JSP文件
    在这里插入图片描述

  2. 编写HTML标签和Java代码
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第2张图片

案例:

<html>
<head>
    <title>Titletitle>
head>
<body>
    <h1>JSP,helloh1>
    <%
        System.out.println("hello jsp");
    %>
body>
html>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第3张图片

1.2 JSP原理

  • JSP本质上就是一个Servlet
  • JSP在被访问时,由JSP容器(Tomcat)将其转换为Java文件(Servlet),在由JSP容器(Tomcat)将其编译,最终对外提供服务的其实就是这个字节码文件
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第4张图片

1.3 JSP脚本

  • JSP脚本用于在JSP页面内定义Java代码.
  • JSP脚本分类:
    1、 <%...%>:内容会直接放到_jspService()方法之中
    2、<%=...%>:内容会放到out.print()中,作为out.print()的参数
    3、<%!..%>:内容会放到_jspService()方法之外,被类直接包含

例子:
注意使用maven插件的tomcat7运行时最好对应的jdk版本为1.8,如果jdk版本太高可能会出现jsp编译不了的情况(500报错之一)
解决方案:

    • 1.在设置里面,Build->创建工具->Maven->运行程序下找到JRE条件jdk版本
    • 2.自行在创建项目时使用低版本的jdk
    • 3.具体分析java语法变换,下例情况去掉System
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/7/31
  Time: 9:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>JSP,hello</h1>
    <%
        out.println("hello,jsp");
        int i = 3;
    %>

    <%="hello"%>
    <%=i%>

    <%!
        void show(){}
        String name = "zhangsan";
    %>
</body>
</html>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第5张图片
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第6张图片

练习:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第7张图片
Brand类:

package com.itheima.pojo;

/**
 * 品牌实体类
 */

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, String description) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.description = description;
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

brand.jsp:

<%@ page import="com.itheima.pojo.Brand" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/1
  Time: 12:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    //查询数据库
    List<Brand> brands = new ArrayList<Brand>();
    brands.add(new Brand(1,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1));
    brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0));
    brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1));
%>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
    <tr>
        <th>序号</th>
        <th>品牌名称</th>
        <th>企业名称</th>
        <th>排序</th>
        <th>品牌介绍</th>
        <th>状态</th>
        <th>操作</th>

    </tr>


   <%
       for (int i = 0; i < brands.size(); i++) {
           Brand brand = brands.get(i);
   %>
    <tr align="center">
        <td><%=brand.getId()%></td>
        <td><%=brand.getBrandName()%></td>
        <td><%=brand.getCompanyName()%></td>
        <td><%=brand.getOrdered()%></td>
        <td><%=brand.getDescription()%></td>

        <%
            if(brand.getStatus()==1){
                //显示启用
        %>
            <td><%="启用"%></td>
        <%
            }else {
                //显示禁用
        %>
            <td><%="禁用"%></td>
        <%
            }
        %>
        
        <td><a href="#">修改</a> <a href="#">删除</a></td>
    </tr>
   <%
       }
   %>


</table>

</body>
</html>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第8张图片

1.3.1 JSP缺点

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第9张图片

由于JSP页面内,既可以定义HTML标签,又可以定义Java代码,造成了以下问题:

  1. 书写麻烦:特别是复杂的页面
  2. 阅读麻烦
  3. 复杂度高:运行需要依赖于各种环境,JRE,JSP容器,JavaEE…
  4. 占内存和磁盘:JSP会自动生成.java和.class文件占磁盘,运行的是.class文件占内存
  5. 调试困难:出错后,需要找到自动生成的.java文件进行调试
  6. 不利于团队协作:前端人员不会Java,后端人员不精HTML

演变过程:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第10张图片

1.4 EL 表达式

Expression Language表达式语言,用于简化JSP页面内的Java代码

  • 主要功能:获取数据

语法:${expression}
${brands}:获取域中存储的key为brands的数据

JavaWeb中的四大域对象:

  1. page:当前页面有效
  2. request:当前请求有效
  3. session:当前会话有效
  4. application:当前应用有效

例子:
ServletDemo1:

@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.准备数据
        List<Brand> brands = new ArrayList<Brand>();
        brands.add(new Brand(1,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1));
        brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0));
        brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1));

        //2.储存到request域中
        request.setAttribute("brands",brands);

        //3.转发到el-demo.jsp
        request.getRequestDispatcher("/el-demo.jsp").forward(request,response);


    }

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

el-demo.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${brands}

</body>
</html>

如果只是显示 ${brands}的话,在头部加上isELIgnored="false"即可
在这里插入图片描述

el表达式获取数据,会依次从这4个域中寻找,直到找到为止
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第11张图片

1.5 JSTL 标签

JSP标准标签库(Jsp Standarded Tag Library),使用标签取代JSP页面上的Java代码

例如:

<c:if test="${flag ==1}"></c:if>
<c:if test="${flag == 2}"></c:if>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第12张图片

1.5.1 JSTL 快速入门

  1. 导入坐标
<dependency>
	<groupId>jstlgroupId>
	<artifactId>jstl<lartifactId>
	<version>1.2version>
dependency>
<dependency>
	<groupId>taglibsgroupId>
	<artifactId>standardartifactId>
	<version>1.1.2version>
dependency>
  1. 在JSP页面上引入JSTL标签库
<%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %>
  1. 使用

1.5.1 - I JSTL标签if

例子:
ServletDemo1类修改部分:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第13张图片
jstl-if.jsp:

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

<head>
    <title>Title</title>
</head>
<body>
<%--
    c:if 来完成逻辑判断,替换java if else
--%>

<%--    <c:if test="true">--%>
<%--        <h1>true</h1>--%>
<%--    </c:if>--%>
<%--    <c:if test="false">--%>
<%--        <h1>false</h1>--%>
<%--    </c:if>--%>

        <c:if test="${status ==1}">
            启用
        </c:if>
        <c:if test="${status ==0}">
            禁用
        </c:if>
</body>
</html>

显示如果空白的话,添加:isELIgnored=“false”
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第14张图片

1.5.1 - II JSTL标签forEach

:相当于for循环

  • items:被遍历的容器
  • var:遍历产生的临时变量
  • varStatus:遍历状态对象
  • count:从1开始遍历的数字
  • status:从0开始遍历的数字
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第15张图片

例子:

<%@ 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</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
  <tr>
    <th>序号</th>
    <th>品牌名称</th>
    <th>企业名称</th>
    <th>排序</th>
    <th>品牌介绍</th>
    <th>状态</th>
    <th>操作</th>

  </tr>

  <c:forEach items="${brands}" var="brand" varStatus="status">
    <tr align="center">
<%--      <td>${brand.id}</td>--%>
      <td>${status.count}</td>
      <td>${brand.brandName}</td>
      <td>${brand.companyName}</td>
      <td>${brand.ordered}</td>
      <td>${brand.description}</td>

      <c:if test="${brand.status==1}">
        <td>启用</td>
      </c:if>
      <c:if test="${brand.status != 1}">
        <td>禁用</td>
      </c:if>
      <td><a href="#">修改</a> <a href="#">删除</a></td>
    </tr>
  </c:forEach>


</table>

</body>
</html>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第16张图片

  • begin:开始数
  • end:结束数
  • step:步长
    在这里插入图片描述

例子:

<c:forEach begin="1" end="10" step="1" var="i">
<%--  ${i}<br>--%>
  <a href="#">${i}</a>
</c:forEach>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第17张图片

1.6 MVC模式

MVC是一种分层开发的模式,其中:

  • M: Model,业务模型,处理业务
  • V: View,视图,界面展示
  • C: Controller,控制器,处理请求,调用模型和视图
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第18张图片

MVC好处:

  1. 职责单一,互不影响
  2. 有利于分工协作
  3. 有利于组件重用

1.7 三层架构

  • 数据访问层:对数据库的CRUD基本操作
  • 业务逻辑层:对业务逻辑进行封装,组合数据访问层层中基本功能,形成复杂的业务逻辑功能
  • 表现层:接收请求,封装数据,调用业务逻辑层,响应数据
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第19张图片

MVC和三层架构的区别:

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第20张图片

1.8 实现案例

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第21张图片

1.8.1 环境准备

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第22张图片

  • 核心配置文件pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>brand-demoartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <properties>
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>
    properties>

    <dependencies>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>


        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.30version>
        dependency>


        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>


        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
            <scope>providedscope>
        dependency>


        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>


        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
            plugin>
        plugins>
    build>
project>
  • 创建目录结构包:
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第23张图片

  • 数据库的创建:

-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);


SELECT * FROM tb_brand;
  • pojo下的Brand实体类
package com.itheima.pojo;

/**
 * 品牌实体类
 */

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, String description) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.description = description;
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}
  • mybatis-config.xml

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <typeAliases>
        <package name="com.itheima.pojo"/>
    typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        <package name="com.itheima.mapper"/>
    mappers>
configuration>
  • BrandMapper.xml

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">

mapper>
  • BrandMapper.java
package com.itheima.mapper;

public interface BrandMapper {
}

目录展示:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第24张图片

1.8.2 查询所有

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第25张图片

  • brand.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/2
  Time: 9:59
  To change this template use File | Settings | File Templates.
--%>
<%@ 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>Titletitle>
head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
  <tr>
    <th>序号th>
    <th>品牌名称th>
    <th>企业名称th>
    <th>排序th>
    <th>品牌介绍th>
    <th>状态th>
    <th>操作th>

  tr>

  <c:forEach items="${brands}" var="brand" varStatus="status">
    <tr align="center">
<%--      <td>${brand.id}td>--%>
      <td>${status.count}td>
      <td>${brand.brandName}td>
      <td>${brand.companyName}td>
      <td>${brand.ordered}td>
      <td>${brand.description}td>

      <c:if test="${brand.status==1}">
        <td>启用td>
      c:if>
      <c:if test="${brand.status != 1}">
        <td>禁用td>
      c:if>
      <td><a href="#">修改a> <a href="#">删除a>td>
    tr>
  c:forEach>


table>


body>
html>
  • BrandMapper.xml

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName">result>
        <result column="company_name" property="companyName">result>
    resultMap>
mapper>
  • BrandMapper.java
package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface BrandMapper {

    //查询所有
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();
}

  • BrandService.java
public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

   //查询所有功能
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

       //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();

        return brands;
    }
}

  • index.html
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <a href="/brand-demo/selectAllServlet">查询所有a>
body>
html>
  • SqlSessionFactoryUtils 类:
ublic class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //静态代码块会随着类的加载而自动执行,且只执行一次

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

  • selectAllServlet:
@WebServlet("/selectAllServlet")
public class selectAllServlet extends HttpServlet {
    private BrandService service = new BrandService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.调用BrandService完成查询
        List<Brand> brands = service.selectAll();

        //2.存入request域中
        request.setAttribute("brands",brands);

        //3.转发到brand.jsp
        request.getRequestDispatcher("/brand.jsp").forward(request,response);

    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第26张图片

1.8.3 添加数据

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第27张图片

  • brand.jsp:
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/2
  Time: 9:59
  To change this template use File | Settings | File Templates.
--%>
<%@ 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>Titletitle>
head>
<body>
<input type="button" value="新增" id="add"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
  <tr>
    <th>序号th>
    <th>品牌名称th>
    <th>企业名称th>
    <th>排序th>
    <th>品牌介绍th>
    <th>状态th>
    <th>操作th>

  tr>

  <c:forEach items="${brands}" var="brand" varStatus="status">
    <tr align="center">
<%--      <td>${brand.id}td>--%>
      <td>${status.count}td>
      <td>${brand.brandName}td>
      <td>${brand.companyName}td>
      <td>${brand.ordered}td>
      <td>${brand.description}td>

      <c:if test="${brand.status==1}">
        <td>启用td>
      c:if>
      <c:if test="${brand.status != 1}">
        <td>禁用td>
      c:if>
      <td><a href="#">修改a> <a href="#">删除a>td>
    tr>
  c:forEach>


table>

<script>
  document.getElementById("add").onclick = function (){
    location.href="/brand-demo/addBrand.jsp ";
  }
script>

body>
html>
  • BrandMapper.java
public interface BrandMapper {

    //查询所有
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);
}

  • BrandService.java
public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

   //查询所有功能
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

       //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();

        return brands;
    }

    public void add(Brand brand){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.add(brand);

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

}

  • addBrand.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/2
  Time: 21:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>添加品牌title>
head>
<body>
<h3>添加品牌h3>
<form action="/brand-demo/AddServlet" method="post">
  品牌名称:<input name="brandName"><br>
  企业名称:<input name="companyName"><br>
  排序:<input name="ordered"><br>
  描述信息:<textarea rows="5" cols="20" name="description">textarea><br>
  状态:
  <input type="radio" name="status" value="0">禁用
  <input type="radio" name="status" value="1">启用<br>

  <input type="submit" value="提交">
form>
body>
html>
  • AddServlet.java
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
   private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理post请求乱码问题
        request.setCharacterEncoding("utf-8");

        //1.结束表单提交的数据,封装为一个Brand妒忌心
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        //封装为一个Brand对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //2.调用service 完成添加操作
        service.add(brand);

        //3.转发到查询所有Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第28张图片

1.8.4 修改

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第29张图片

1.8.4 - I 修改回显数据

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第30张图片

  • BrandMapper.java
public interface BrandMapper {

    //查询所有
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    //根据id查询
    @Select("select * from tb_brand where id = #{id}")
    @ResultMap("brandResultMap")
    Brand selectById(int id);

}

  • update.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/2
  Time: 21:22
  To change this template use File | Settings | File Templates.
--%>
<%@ 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>
head>
<body>
<h3>修改品牌h3>
<form action="/brand-demo/AddServlet" method="post">
  品牌名称:<input name="brandName" value="${brand.brandName}"><br>
  企业名称:<input name="companyName" value="${brand.companyName}"><br>
  排序:<input name="ordered" value="${brand.ordered}"><br>
  描述信息:<textarea rows="5" cols="20" name="description"> value="${brand.description}"textarea><br>
  状态:
  <c:if test="${brand.status == 0}">
    <input type="radio" name="status" value="0" checked>禁用
    <input type="radio" name="status" value="1">启用<br>
  c:if>

  <c:if test="${brand.status == 1}">
    <input type="radio" name="status" value="0">禁用
    <input type="radio" name="status" value="1"  checked>启用<br>
  c:if>

  <input type="submit" value="提交">
form>
body>
html>
  • selectByIdServlet
WebServlet("/selectByIdServlet")
public class selectByIdServlet extends HttpServlet {
    private BrandService service = new BrandService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收id
        String id = request.getParameter("id");
        //2.调用serivce查询
        Brand brand = service.selectById(Integer.parseInt(id));

        //3.存储到request中
        request.setAttribute("brand",brand);
        //4.转发到update.jsp
        request.getRequestDispatcher("/update.jsp").forward(request,response);

    }

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

  • BrandService
public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

   //查询所有功能
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

       //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();

        return brands;
    }

    public void add(Brand brand){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.add(brand);

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

    //根据id查询
    public Brand selectById(int id){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        Brand brand = mapper.selectById(id);

        sqlSession.close();

        return brand;
    }
}

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第31张图片

1.8.4 - II 修改数据

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第32张图片

  • BrandMapper.java
public interface BrandMapper {

    //查询所有
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    //根据id查询
    @Select("select * from tb_brand where id = #{id}")
    @ResultMap("brandResultMap")
    Brand selectById(int id);

    //修改
    @Update("update tb_brand set brand_name = #{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}")
    void update(Brand brand);
}

  • updateService.java
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
   private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理post请求乱码问题
        request.setCharacterEncoding("utf-8");

        //1.结束表单提交的数据,封装为一个Brand妒忌心
       String id = request.getParameter("id");
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        //封装为一个Brand对象
        Brand brand = new Brand();
        brand.setId(Integer.parseInt(id));
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //2.调用service 完成添加操作
        service.update(brand);

        //3.转发到查询所有Servlet
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

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

  • BrandService.java
public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

   //查询所有功能
    public List<Brand> selectAll(){
        //调用BrandMapper.selectAll()

       //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();

        return brands;
    }

    //添加
    public void add(Brand brand){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.add(brand);

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

    //根据id查询
    public Brand selectById(int id){
        //调用BrandMapper.selectAll()

        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        Brand brand = mapper.selectById(id);

        sqlSession.close();

        return brand;
    }

    //添加
    public void update(Brand brand){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.update(brand);

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

}

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第33张图片

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第34张图片

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第35张图片

2. 会话跟踪技术

  • 会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。在一次会话中可以包含多次请求和响应
  • 会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一浏览器,以便于在同一次会话的多次请求间共享数据
  • HTTP协议是无状态的,每次浏览器向服务器请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话数据共享
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第36张图片

实现方式:

  1. 客户端会话跟踪技术:Cookie
  2. 服务端会话跟踪技术:Session

2.1 Cookie

2.1.1 Cookie基本使用

Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问

基本使用:
发送Cookie:

  1. 创建Cookie对象,设置数据
Cookie cookie = new Cookie("key","value");
  1. 发送Cookie到客户端:使用response对象
response.addCookie(cookie);

例如:

@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //发送cookie

        //1.创建cookie对象
        Cookie cookie = new Cookie("username", "zs");

        //2.发送Cookie.response
        response.addCookie(cookie);
    }

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

获取Cookie:

  1. 获取客户端携带的所有Cookie,使用request对象
Cookie[] cookies = request.getCookies();
  1. 遍历数组,获取每一个Cookie对象:for
cookie.getName();
  1. 使用Cookie对象方法获取数据
cookie.getName();
cookie.getValue();

例子:

@WebServlet("/bServlet")
public class bServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取cookie
        //1.获取Cookie数组
        Cookie[] cookies = request.getCookies();

        //2.遍历数组
        for (Cookie cookie : cookies) {
            //3.获取数据
            String name = cookie.getName();

            if("username".equals(name)){
                String value = cookie.getValue();
                System.out.println(name+":"+value);
                break;
            }
        }
    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第37张图片
接收aServlet的cookie
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第38张图片

2.1.2 Cookie原理

cookie的实现是基于HTTP协议的:

  • 响应头:set-cookie
  • 请求头:cookie
    小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第39张图片

2.1.3 Cookie使用细节

Cookie存活时间:

  • 默认情况下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,则Cookie被销毁
  • setMaxAge(int seconds):设置Cookie存活时间
    • 1、正数:将Cookie写入浏览器所在电脑的硬盘,持久化存储。到时间自动删除
    • 2、负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,则Cookie被销毁
    • 3、零:删除对应Cookie

例子:

@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //发送cookie

        //1.创建cookie对象
        Cookie cookie = new Cookie("username", "vanwot");

        //设置存活时间 7天
        cookie.setMaxAge((60*60*24*7));

        //2.发送Cookie.response
        response.addCookie(cookie);
    }

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

在这里插入图片描述

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第40张图片

Cookie存储中文:

  • Cookie不能直接存储中文
  • 如果需要存储,则需要进行转码:URL编码
//编码
 value = URLDecoder.encode(value,"UTF-8");
//解码
 value = URLDecoder.decode(value,"UTF-8");

例子:
aServelt:

@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //发送cookie
        //1.创建cookie对象

        String value= "麻瓜";
        //URL编码
       value = URLEncoder.encode(value,"utf-8");

        System.out.println("储存数据:"+value);
        Cookie cookie = new Cookie("username", value);

        //设置存活时间 7天
        cookie.setMaxAge((60*60*24*7));

        //2.发送Cookie.response
        response.addCookie(cookie);
    }

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

bServlet:

@WebServlet("/bServlet")
public class bServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取cookie
        //1.获取Cookie数组
        Cookie[] cookies = request.getCookies();

        //2.遍历数组
        for (Cookie cookie : cookies) {
            //3.获取数据
            String name = cookie.getName();

            if("username".equals(name)){
                String value = cookie.getValue();
                System.out.println(name+":"+value);

                //URL解码
                value = URLDecoder.decode(value,"utf-8");
                System.out.println(name+":"+value);
                break;
            }
        }
    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第41张图片

2.2 Session

2.2.1 Session基本使用

服务端会话跟踪技术:将数据保存到服务端
JavaEE提供HttpSession接口,来实现一次会话的多次请求间数据共享功能

使用:

  1. 获取Session对象
HttpSession session = request.getSession();
  1. Session对象功能:
    • void setAttribute(String name, Object o):存储数据到session域中
    • Object getAttribute(String name):根据key,获取值
    • void removeAttribute(String name):根据key,删除该键值对
      小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第42张图片

例子:
SessionDemo1:

@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //存储到Session中
        //1.获取Session对象
        HttpSession session = request.getSession();

        //2.存储数据
        session.setAttribute("username","vanwot");
    }

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

SessionDemo2:

@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取数据,从session中
        //1.获取Session对象
        HttpSession session = request.getSession();
        //2.获取数据
        Object username = session.getAttribute("username");
        System.out.println(username);
    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第43张图片

2.2.2 Session原理

Session是基于Cookie实现的
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第44张图片

2.2.3 Session使用细节

Session钝化、活化:

  • 服务器重启后,Session中的数据是否还在?
  • 钝化:在服务器正常关闭后,Tomcat会自动将Session数据写入硬盘的文件中
  • 活化:再次启动服务器后,从文件中加载数据到Session中

Seesion销毁:

  • 默认情况下,无操作,30分钟自动销毁
    • 配置在web-xml文件中
<session-config>
	<session-timeout>30session-timeout>
session-config>
  • 调用Session对象的invalidate()方法

2.3 小结

Cookie和Session都是完成一次会话内多次请求间数据共享的

其区别:

  • 存储位置:Cookie是将数据存储在客户端,Session将数据存储在服务端
  • 安全性:Cookie不安全,Session安全
  • 数据大小:Cookie最大3KB,Session无大小限制
  • 存储时间:Cookie可以长期存储,Session默认30分钟
  • 服务器性能:Cookie不占服务器资源,Session占用服务器资源

2.4 案例

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第45张图片

2.4.1 用户登录

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第46张图片
在brand-demo的webapp下导入原来的:
在这里插入图片描述
UserMapper:

public interface UserMapper {


    /**
     * 根据用户名和密码查询用户对象
     * @param username
     * @param password
     * @return
     */
    @Select("select * from tb_user where username = #{username} and password = #{password}")
    User select(@Param("username") String username,@Param("password")  String password);

    /**
     * 根据用户名查询用户对象
     * @param username
     * @return
     */
    @Select("select * from tb_user where username = #{username}")
    User selectByUsername(String username);

    /**
     * 添加用户
     * @param user
     */
    @Insert("insert into tb_user values(null,#{username},#{password})")
    void add(User user);
}

User实体类:

public class User {

    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

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

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">

mapper>

UserService:

public class UserService {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    //登录方法
    public User login(String username,String password){
        //2.获取SqlSession
        SqlSession sqlSession = factory.openSession();

        //3.获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4.调用方法
        User user = mapper.select(username, password);
        sqlSession.close();
        return user;
    }
}

loginServlet:

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2.调用service查询
         User user = service.login(username,password);

         //3.判断
        if(user !=null){
            //登录成功,跳转到查询所有的BrandServlet

            //将登录成功后的user对象,储存到Session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);


            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectAllServlet");


        }else {
            //登录失败

            //存储错误信息到request
            request.setAttribute("login_msg","用户名或密码错误");

            //跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

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

用户名和密码错误时:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第47张图片
正确时:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第48张图片

2.4.2 记住用户

2.4.2 - I 写cookie

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第49张图片

  • login.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/4
  Time: 23:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


DOCTYPE html>
<html lang="en">

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

<body>
<div id="loginDiv" style="height: 350px">
    <form action="/brand-demo/loginServlet" id="form">
        <h1 id="loginMsg">LOGIN INh1>
        <div id="errorMsg">${login_msg}div>
        <p>Username:<input id="username" name="username" type="text">p>

        <p>Password:<input id="password" name="password" type="password">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="register.html">没有账号?a>
        div>
    form>
div>

body>
html>
  • loginService
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

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


        //2.调用service查询
         User user = service.login(username,password);

         //3.判断
        if(user !=null){
            //登录成功,跳转到查询所有的BrandServlet

            //判断用户是否勾选记住我
            if ("1".equals(remenber)){
                //勾选了,发送cookie对象

                //1.创建cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);

                //设置cookie存活时间
                c_username.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);

                //2.发送
                response.addCookie(c_username);
                response.addCookie(c_password);

            }


            //将登录成功后的user对象,储存到Session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);


            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectAllServlet");


        }else {
            //登录失败

            //存储错误信息到request
            request.setAttribute("login_msg","用户名或密码错误");

            //跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

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

勾选登录成功后:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第50张图片

2.4.2 - II 获取cookie

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第51张图片

刷新后:

  • login.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/4
  Time: 23:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


DOCTYPE html>
<html lang="en">

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

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

        <p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password">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="register.html">没有账号?a>
        div>
    form>
div>

body>
html>

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第52张图片

2.4.3 用户注册

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第53张图片
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第54张图片

  • register.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/5
  Time: 10:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


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="login.html">登录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}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 src="imgs/a.jpg">
          <a href="#" id="changeImg">看不清?a>
        td>
      tr>

    table>

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

div>
body>
html>
  • registerService
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 service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取用户和密码数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //2.调用service 注册
        boolean flag = service.register(user);
        //3.判断注册成功与否
        if(flag){
            //注册成功,跳转登录页面
            request.setAttribute("register_msg","注册成功,请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }else{
            //注册失败
            request.setAttribute("register_msg","用户已经存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

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

  • login.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/4
  Time: 23:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


DOCTYPE html>
<html lang="en">

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

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

        <p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password">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="register.jsp">没有账号?a>
        div>
    form>
div>

body>
html>

成功:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第55张图片
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第56张图片
失败:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第57张图片

2.4.4 验证码

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第58张图片

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.*;
import java.util.Arrays;
import java.util.Random;

/**
 * 生成验证码工具类
 */
public class CheckCodeUtil {

    public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static Random random = new Random();

    public static void main(String[] args) throws IOException {
        OutputStream fos = new FileOutputStream("E://JSP-demo1/brand-demo/src/main/webapp/imgs/a.jpg");
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);

        System.out.println(checkCode);
    }


    /**
     * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
     *
     * @param width 图片宽度
     * @param height   图片高度
     * @param os    输出流
     * @param verifySize    数据长度
     * @return  验证码
     * @throws IOException
     */
    public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(width, height, 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);
            }

        }

    }
}


小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第59张图片
验证码图片会跟随变化:
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第60张图片

  • register.jsp
<%--
  Created by IntelliJ IDEA.
  User: 19148
  Date: 2023/8/5
  Time: 10:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


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="login.html">登录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}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>
  • checkCodeServlet
@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);

    }

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

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第61张图片
小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第62张图片

2.4.4 - I 校验验证码

小黑子—JavaWeb:第五章 - JSP与会话跟踪技术_第63张图片
registerServlet:

@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取用户和密码数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");

        //程序生成的验证码,从Session获取
        HttpSession session = request.getSession();
       String checkCodeGen = (String) session.getAttribute("checkCodeGen");


        User user = new User();
        user.setUsername(username);
        user.setPassword(password);


        //2.调用service 注册
        boolean flag = service.register(user);


        //3.判断注册成功与否
        if(flag){
            //注册成功,跳转登录页面
            request.setAttribute("register_msg","注册成功,请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            //比对验证码
            if(!checkCodeGen.equalsIgnoreCase(checkCode)){
                request.setAttribute("register_msg","验证码错误");
                request.getRequestDispatcher("/register.jsp").forward(request,response);

                //不允许注册
                return;
            }

        }else{
            //注册失败
            request.setAttribute("register_msg","用户已经存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);

        }
    }

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

你可能感兴趣的:(JavaWeb,java,开发语言,jsp)