小黑子—JavaWeb:第七章 - Vue 与 Element 综合案例

news2024/10/6 0:28:56

JavaWeb入门7.0

  • 1. VUE
    • 1.1 Vue 快速入门
    • 1.2 Vue 常用指令
      • 1.2.1 v-bind
      • 1.2.2 v-model
      • 1.2.3 v-on
      • 1.2.4 v-if
      • 1.2.5 v-show
      • 1.2.6 v-for
    • 1.3 Vue 生命周期
    • 1.4 Vue案例
      • 1.4.1 查询所有
      • 1.4.2 新增品牌
  • 2. Element
    • 2.1 Element快速入门
    • 2.2 Element布局
    • 2.3 Element 常用组件
      • 2.3.1 表格
      • 2.3.2 表单
      • 2.3.3 对话框和表单
      • 2.3.4 分页工具条
  • 3. 综合案例
    • 3.1 环境搭建
    • 3.2 查询所有
    • 3.3 新增品牌
    • 3.4 Servlet 代码优化
    • 3.5 批量删除
    • 3.6 分页查询
      • 3.6.1 分析
      • 3.6.2 后端&前端
    • 3.7 条件查询
      • 3.7.1 后端
      • 3.7.2 前端

1. VUE

Vue是一套前端框架,免除原生JavaScript中的DOM操作,简化书写
基于MVVM(Model-View-ViewModel)思想,实现数据的双向绑定,将编程的关注点放在数据上

vue官网

在这里插入图片描述

1.1 Vue 快速入门

  1. 新建HTML页面,引入 Vue.js文件
<script src="js/vue.js"></script>
  1. 在JS代码区域,创建Vue核心对象,进行数据绑定
new Vue({
	el: "#app",
	data() {
		return {
			username: ""
		}
	}
});
  1. 编写视图
<div id="app">
<input name="username" v-model="username" >
	{{username}}
</div>

使用:
导入vue.js文件

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <input v-model="username">
<!--    插值表达式-->
    {{username}}
</div>

<script src="js/vue.js"></script>
<script>
    //1.创建vue核心对象
    // new Vue({
    //     data:function (){
    //         return{
    //             username:""
    //         }
    //     }
    // })

    new Vue({
        el:"#app",
        data(){
            return{
                username:""
            }
        }
    })

</script>

</body>
</html>

在这里插入图片描述

1.2 Vue 常用指令

  • 指令:HTML标签上带有v-前缀的特殊属性,不同指令具有不同含义。
    例如: v-if, v-for…
  • 常用指令
    在这里插入图片描述
    在这里插入图片描述

1.2.1 v-bind

<a v-bind:href="url">百度一下</a>
<!--v-bind可以省略-->
<a :href="url">百度一下</a>

1.2.2 v-model

<input name="username" v-model="username">

1.2.3 v-on

指令作用
v-on为HTML标签绑定事件

使用方式:

  • html:
<input type="button" value="一个按钮" v-on:click="show()">
<input type="button" value="一个按钮" @click="show()">
  • vue
new Vue({
	el:"#app",
	methods: {
		show(){
			alert(我被点了");
		}
	}
});

在这里插入图片描述

1.2.4 v-if

<div v-if="count == 3">div1</div>
<div v-else-if="count == 2">div2</div>
<div v-else>div3</div>

1.2.5 v-show

<div v-show="count == 3">div4</div>

1.2.6 v-for

指令作用
v-for列表渲染,遍历容器的元素或者对象的属性
  • v-for
<div v-for="addr in addrs">
{{addr}}<br>
</div>
  • 加索引
<div v-for="(addr,i) in addrs">
<!--i表示索引,从0开始-->
{{i+1}}:{{addr}}<br>
</div>

1.3 Vue 生命周期

生命周期的八个阶段:每触发一个生命周期事件,会自动执行一个生命周期方法(钩子)

在这里插入图片描述

状态阶段周期
beforeCreate创建前
created创建后
beforeMount载入前
mounted挂载完成
beforeUpdate更新前
updated更新后
beforeDestroy销毁前
destroyed销毁后

mounted:挂载完成,Vue初始化成功,HTML页面渲染成功。

  • 发送异步请求,加载数据

示例:

new Vue({
	el:"#app",
	mounted(){
		alert("vue挂载完毕,发送异步请求");
	}
});

1.4 Vue案例

1.4.1 查询所有

在这里插入图片描述

1.4.2 新增品牌

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>品牌列表</title>
    <!--引入vue.js-->
    <script src="js/vue.js"></script>

    <!--引入 element js css-->
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="element-ui/lib/index.js"></script>
    <script src="js/axios-0.18.0.js"></script>


    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 78px;
            height: 78px;
            line-height: 78px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>

</head>
<body>
<div id="app">


    <el-form :inline="true" :model="searchForm" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="searchForm.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="企业名称">
            <el-input v-model="searchForm.companyName" placeholder="企业名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌名称">
            <el-input v-model="searchForm.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit()">查询</el-button>
        </el-form-item>
    </el-form>

    <el-button type="danger"  @click="delBatch()" plain>批量删除</el-button>
    <el-button type="primary" @click="dialogVisible = true" plain>新增</el-button>


    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @select="checkSelect"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    align="center"
                    prop="brandName"
                    label="品牌名称">
            </el-table-column>

            <el-table-column
                    align="center"
                    prop="companyName"
                    label="企业名称">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="ordered"
                    label="排序">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="statusStr"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    prop="operation"
                    label="操作">
                <el-button type="primary" size="small" @click="updateBrand()">修改</el-button>
                <el-button type="danger" size="small">删除</el-button>
            </el-table-column>
        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10,15 , 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>


    <!--添加/修改表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
        <el-form :model="brandForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

            <el-form-item label="品牌名称" prop="brandName">
                <el-input v-model="brandForm.brandName"></el-input>
            </el-form-item>
            <el-form-item label="企业名称" prop="companyName">
                <el-input v-model="brandForm.companyName"></el-input>
            </el-form-item>
            <el-form-item label="排序">
                <el-input v-model="brandForm.ordered"></el-input>
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="brandForm.description"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-switch
                        :active-value=1
                        :inactive-value=0
                        v-model="brandForm.status">
                </el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('brandForm')">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</div>


<script>
    new Vue({
        el: "#app",
        methods: {
            //每页显示条数发生变化
            handleSizeChange(val) {
               console.log(val)

            },
            //当前页发生变化
            handleCurrentChange(val) {
                //console.log(`当前页: ${val}`);

            },

            submitForm() {
                //console.log(JSON.stringify(this.brandForm));

            },
            //点击查询按钮
            onSubmit() {
                // console.log(this.searchForm);

            },
            handleClose() {
                this.dialogVisible = false;
            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            //批量删除
            delBatch(){


            },
            //选中复选框
            checkSelect(data){
                //console.log(`选中项数据:${data}`)

            },
            //修改
            updateBrand() {
                //弹出编辑窗口
                this.dialogVisible = true;


            }
        },
        data() {
            return {
                checkedBrands:[],
                total: 400,
                currentPage: 1,
                pageSize: 5,
                dialogVisible: false,
                tableData: [{
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                }, {
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                }, {
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                }, {
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                }, {
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                }, {
                    id: 1,
                    brandName: '小米',
                    companyName: '小米科技有限公司',
                    ordered: 10,
                    status: 1,
                    statusStr: "启用",
                    description: "小米"
                },],
                value: '',
                searchForm: {
                    companyName: '',
                    brandName: '',
                    status: ''
                },
                brandForm: {
                    id: '',
                    brandName: '',
                    companyName: '',
                    ordered: '',
                    status: '',
                    description: ""
                },
                rules: {
                    brandName: [
                        {required: true, message: '请输入品牌名称', trigger: 'blur'},
                        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                    ],
                    companyName: [
                        {required: true, message: '请输入企业名称', trigger: 'blur'}
                    ]
                }

            }
        }
    });
</script>
</body>
</html>

2. Element

  • Element:是饿了么公司前端开发团队提供的一套基于Vue的网站组件库,用于快速构建网页

  • 组件:组成网页的部件,例如超链接、按钮、图片、表格等等~

Element官网
在这里插入图片描述

2.1 Element快速入门

  1. 引入Element 的css、js文件和Vue.js
<script src="vue.js"></script>
<script src="element-ui/liblindex.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
  1. 创建Vue核心对象
<script>
new Vue({
		el:"#app"
	})
</script>
  1. 官网复制Element组件代码

例子:
导入的element-ui资源:
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <el-row>
<!--        <el-button>默认按钮</el-button>-->
<!--        <el-button type="primary">主要按钮</el-button>-->
<!--        <el-button type="success">成功按钮</el-button>-->
<!--        <el-button type="info">信息按钮</el-button>-->
<!--        <el-button type="warning">警告按钮</el-button>-->
        <el-button type="danger">删除</el-button>
    </el-row>

<!--    <el-row>-->
<!--        <el-button plain>朴素按钮</el-button>-->
<!--        <el-button type="primary" plain>主要按钮</el-button>-->
<!--        <el-button type="success" plain>成功按钮</el-button>-->
<!--        <el-button type="info" plain>信息按钮</el-button>-->
<!--        <el-button type="warning" plain>警告按钮</el-button>-->
<!--        <el-button type="danger" plain>危险按钮</el-button>-->
<!--    </el-row>-->

<!--    <el-row>-->
<!--        <el-button round>圆角按钮</el-button>-->
<!--        <el-button type="primary" round>主要按钮</el-button>-->
<!--        <el-button type="success" round>成功按钮</el-button>-->
<!--        <el-button type="info" round>信息按钮</el-button>-->
<!--        <el-button type="warning" round>警告按钮</el-button>-->
<!--        <el-button type="danger" round>危险按钮</el-button>-->
<!--    </el-row>-->

<!--    <el-row>-->
<!--        <el-button icon="el-icon-search" circle></el-button>-->
<!--        <el-button type="primary" icon="el-icon-edit" circle></el-button>-->
<!--        <el-button type="success" icon="el-icon-check" circle></el-button>-->
<!--        <el-button type="info" icon="el-icon-message" circle></el-button>-->
<!--        <el-button type="warning" icon="el-icon-star-off" circle></el-button>-->
<!--        <el-button type="danger" icon="el-icon-delete" circle></el-button>-->
<!--    </el-row>-->





</div>

<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">


<script>
    new Vue({
        el:"#app"
    })
</script>



</body>
</html>

在这里插入图片描述

2.2 Element布局

Element中有两种布局方式:

  1. Layout布局:通过基础的24分栏,迅速简便地创建布局
    在这里插入图片描述

  2. Container 布局容器:用于布局的容器组件,方便快速搭建页面的基本结构
    在这里插入图片描述

2.3 Element 常用组件

在Element官网找到相关的组件并且配置到网页中
在这里插入图片描述

2.3.1 表格

2.3.2 表单

2.3.3 对话框和表单

2.3.4 分页工具条

3. 综合案例

在这里插入图片描述

3.1 环境搭建

在这里插入图片描述
数据库准备:

use db1;

-- 删除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 
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '万物互联', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1),
       ('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
       ('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
       ('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
       ('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
       ('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1)
        ;
   

SELECT * FROM tb_brand;

资源准备:
在这里插入图片描述

3.2 查询所有

在这里插入图片描述

  • BrandMapper:
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();
}

  • Brand实现类
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 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 String getStatusStr(){
        if (status == null){
            return "未知";
        }
        return status == 0 ? "禁用":"启用";
    }

    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 +
                '}';
    }
}

  • BrandServiceImpl
package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {

    //1.创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

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

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

        return brands;
    }
}

  • 工具类SqlSessionFactoryUtils
package com.itheima.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public 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;
    }
}

  • selectAllService
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectAllServlet")
public class selectAllServlet extends HttpServlet {

   private BrandService brandService = new BrandServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.调用service查询
        List<Brand> brands = brandService.selectAll();

        //2.转为JSON
        String jsonString = JSON.toJSONString(brands);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

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

  • brand.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain>批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
            >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted(){
            //当页面加载完成后,发送异步请求,获取数据
            var _this = this;

            axios({
                method:"get",
                url:"http://localhost:8080/brand-case/selectAllServlet",

            }).then(function (resp){
                _this.tableData = resp.data;
            })
        },

        methods: {
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand(){
                console.log(this.brand);
            },

            //分页
            handleSizeChange(val) {
                console.log(`每页 ${val}`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            }

        },
        data() {
            return {
                // 当前页码
                currentPage: 4,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>

在这里插入图片描述

3.3 新增品牌

在这里插入图片描述

  • brand.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain>批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
            >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted(){
            //当页面加载完成后,发送异步请求,获取数据
            // var _this = this;
            //
            // axios({
            //     method:"get",
            //     url:"http://localhost:8080/brand-case/selectAllServlet",
            //
            // }).then(function (resp){
            //     _this.tableData = resp.data;
            // })
            this.selectAll();
        },

        methods: {

            //查询所有数据
            selectAll(){
                var _this = this;

                axios({
                    method:"get",
                    url:"http://localhost:8080/brand-case/selectAllServlet",

                }).then(function (resp){
                    _this.tableData = resp.data;
                })
            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand(){
                var _this = this;
                // console.log(this.brand);
                //发送ajax请求,添加数据
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/addServlet",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //添加成功
                        //关闭窗口

                        _this.dialogVisible = false;

                        //然后重新查询
                        _this.selectAll();
                        //提示信息
                        _this.$message({
                            message:'恭喜添加成功',
                            type:'success'
                        });

                    }
                })

            },

            //分页
            handleSizeChange(val) {
                console.log(`每页 ${val}`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            }

        },
        data() {
            return {
                // 当前页码
                currentPage: 4,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>
  • BrandMapper.java
package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.Insert;
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();

    //添加数据
    @Insert("insert into tb_brand value (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);
}

  • BrandService
package com.itheima.service;

import com.itheima.pojo.Brand;

import java.util.List;

public interface BrandService {

      //查询所有
      List<Brand> selectAll();

      //添加数据
      void add(Brand brand);
}

  • BrandServiceImpl
package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {

    //1.创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

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

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

        return brands;
    }

    @Override
    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();

    }
}

  • addServlet
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/addServlet")
public class addServlet extends HttpServlet {
  private BrandService brandService = new BrandServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//jsonzifc

        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);

        //2.调用service添加
        brandService.add(brand);

        //3.响应成功的标志
        response.getWriter().write("success");

    }


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

在这里插入图片描述
在这里插入图片描述

3.4 Servlet 代码优化

  • Web层的Servlet个数太多了,不利于管理和编写
  • 将Servlet进行归类,对应同一个实体的操作方法,写到一个Servlet中。比如:BrandServlet、UserServlet
    在这里插入图片描述

自定义Servlet,使用请求路径进行方法分发,替换HttpServlet的根据请求方式进行方法分发

  • BaseServlet
package com.itheima.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    //根据请求的最后一段路径进行方法分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求路径
        String uri = req.getRequestURI();//brand-case/brand/selectAll
//        System.out.println(uri);
        //2. 获取最后一段路径,方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index+1);

//        System.out.println(methodName);
        //2.执行方法
        //2.1 获取BrandServlet /UserServlet 字节码对象

        //谁调用我(this 所在的方法),我(this)代表谁
//        System.out.println(this);//BrandServlet? httpServlet?  BrandServlet!!

        Class<? extends BaseServlet> cls = this.getClass();

        //2.2 获取方法 Method对象
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //2.3 执行
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}

  • BrandServlet
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;


@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
    private BrandService brandService = new BrandServiceImpl();

   public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.调用service查询
       List<Brand> brands = brandService.selectAll();

       //2.转为JSON
       String jsonString = JSON.toJSONString(brands);

       //3.写数据
       response.setContentType("text/json;charset=utf-8");
       response.getWriter().write(jsonString);
   }

   public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.接收品牌数据
       BufferedReader br = request.getReader();
       String params = br.readLine();//jsonzifc

       //转为Brand对象
       Brand brand = JSON.parseObject(params, Brand.class);

       //2.调用service添加
       brandService.add(brand);

       //3.响应成功的标志
       response.getWriter().write("success");

   }



}

  • UserServlet
package com.itheima.web.servlet;

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


@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

   public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       System.out.println("brand selectAll...");
   }

   public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
       System.out.println("brand add...");
   }



}

  • Brand.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain>批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
            >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted(){
            //当页面加载完成后,发送异步请求,获取数据
            // var _this = this;
            //
            // axios({
            //     method:"get",
            //     url:"http://localhost:8080/brand-case/selectAllServlet",
            //
            // }).then(function (resp){
            //     _this.tableData = resp.data;
            // })
            this.selectAll();
        },

        methods: {

            //查询所有数据
            selectAll(){
                var _this = this;

                axios({
                    method:"get",
                    url:"http://localhost:8080/brand-case/brand/selectAll",

                }).then(function (resp){
                    _this.tableData = resp.data;
                })
            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand(){
                var _this = this;
                // console.log(this.brand);
                //发送ajax请求,添加数据
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/add",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //添加成功
                        //关闭窗口

                        _this.dialogVisible = false;

                        //然后重新查询
                        _this.selectAll();
                        //提示信息
                        _this.$message({
                            message:'恭喜添加成功',
                            type:'success'
                        });

                    }
                })

            },

            //分页
            handleSizeChange(val) {
                console.log(`每页 ${val}`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            }

        },
        data() {
            return {
                // 当前页码
                currentPage: 4,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>

在这里插入图片描述
在这里插入图片描述

3.5 批量删除

在这里插入图片描述

  • brand.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted() {
            //当页面加载完成后,发送异步请求,获取数据
            // var _this = this;
            //
            // axios({
            //     method:"get",
            //     url:"http://localhost:8080/brand-case/selectAllServlet",
            //
            // }).then(function (resp){
            //     _this.tableData = resp.data;
            // })
            this.selectAll();
        },

        methods: {

            //查询所有数据
            selectAll() {
                var _this = this;

                axios({
                    method: "get",
                    url: "http://localhost:8080/brand-case/brand/selectAll",

                }).then(function (resp) {
                    _this.tableData = resp.data;
                })
            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand() {
                var _this = this;
                // console.log(this.brand);
                //发送ajax请求,添加数据
                axios({
                    method: "post",
                    url: "http://localhost:8080/brand-case/brand/add",
                    data: _this.brand
                }).then(function (resp) {
                    if (resp.data == "success") {
                        //添加成功
                        //关闭窗口

                        _this.dialogVisible = false;

                        //然后重新查询
                        _this.selectAll();
                        //提示信息
                        _this.$message({
                            message: '恭喜添加成功',
                            type: 'success'
                        });

                    }
                })

            },

            //分页
            handleSizeChange(val) {
                console.log(`每页 ${val}`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            },

            //完成批量删除
            deleteByIds() {
                //console.log(this.multipleSelection);
                /*
                [
                    {
                        "brandName": "华为",
                        "companyName": "华为技术有限公司",
                        "description": "万物互联",
                        "id": 1,
                        "ordered": 100,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "小米",
                        "companyName": "小米科技有限公司",
                        "description": "are you ok",
                        "id": 2,
                        "ordered": 50,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "格力",
                        "companyName": "格力电器股份有限公司",
                        "description": "让世界爱上中国造",
                        "id": 3,
                        "ordered": 30,
                        "status": 1,
                        "statusStr": "启用"
                    }
                ]
                 */


                //弹出确认提示框
                this.$confirm('此操作将永久删除该文件,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //1.创建id数组[1,2,3] 从this.multipleSelection 获取即可
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = selectionElement.id;

                    }
                    //2.发送AJAX请求
                    var _this = this;

                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteByIds",
                        data: _this.selectedIds
                    }).then(function (resp) {
                        if (resp.data == "success") {
                            //删除成功

                            //然后重新查询
                            _this.selectAll();
                            //提示信息
                            _this.$message({
                                message: '恭喜删除成功',
                                type: 'success'
                            });

                        }
                    })


                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });


            }

        },

        data() {
            return {
                // 当前页码
                currentPage: 4,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id: "",
                    ordered: "",
                    description: ""
                },
                //被选中的id数组
                selectedIds: [],


                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>
  • BrandService
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;


@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
    private BrandService brandService = new BrandServiceImpl();

   public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.调用service查询
       List<Brand> brands = brandService.selectAll();

       //2.转为JSON
       String jsonString = JSON.toJSONString(brands);

       //3.写数据
       response.setContentType("text/json;charset=utf-8");
       response.getWriter().write(jsonString);
   }

   public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.接收品牌数据
       BufferedReader br = request.getReader();
       String params = br.readLine();//jsonzifc

       //转为Brand对象
       Brand brand = JSON.parseObject(params, Brand.class);

       //2.调用service添加
       brandService.add(brand);

       //3.响应成功的标志
       response.getWriter().write("success");

   }


   //批量删除
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//jsonzifc

        //转为int[]
        int[] ids = JSON.parseObject(params, int[].class);

        //2.调用service添加
        brandService.deleteByIds(ids);

        //3.响应成功的标志
        response.getWriter().write("success");

    }

}

  • BrandMapper.java
    //批量删除
    void deleteByIds(@Param("ids") int[] ids);
  • BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!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 property="brandName" column="brand_name" />
        <result property="companyName" column="company_name" />
    </resultMap>


    <delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

</mapper>

在这里插入图片描述

3.6 分页查询

3.6.1 分析

分页查询LIMIT
参数1:开始索引
参数2:查询的条目数

比如:
select * from tb_brand limit 0,5
select * from tb_brand limit 5,5

页面传递的参数
当前页面
每页显示条数

-- 参数1:开始索引 = (当前页面 - 1) - 每页显示条数
-- 参数2:查询的条目数 = 每页显示条数


在这里插入图片描述
准备:

package com.itheima.pojo;

import java.util.List;

//分页查询的JavaBean
public class PagBean<T> {
    //总记录数
    private int totalCount;

    //当前页数据
    private List<T> rows;

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }
}

3.6.2 后端&前端

在这里插入图片描述

  • BrandServiceImpl
package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {

    //1.创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

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

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

        return brands;
    }

    @Override
    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();

    }

    @Override
    public void deleteByIds(int[] ids) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.deleteByIds(ids);

        sqlSession.commit();

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

    @Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
      //2.获取SqlSesion对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.计算开始索引
        int begin = (currentPage - 1) * pageSize;

        //计算查询条目数
        int size = pageSize;

        //5.查询当前页数据
        List<Brand> rows = mapper.selectByPage(begin,size);
        //6.查询总记录数
        int totalCount = mapper.selectTotalCount();

        //7.封装PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

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

        return pageBean;
    }
}

  • BrandService接口
package com.itheima.service;

import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;

import java.util.List;

public interface BrandService {

      //查询所有
      List<Brand> selectAll();

      //添加数据
      void add(Brand brand);

      //批量删除
      void deleteByIds( int[] ids);

      //分页查询
      //currentPage:当前页码
      // pageSize:每页展示条数
      PageBean<Brand> selectByPage(int currentPage,int pageSize);

}

  • BrandServlet
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;


@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
    private BrandService brandService = new BrandServiceImpl();

   public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.调用service查询
       List<Brand> brands = brandService.selectAll();

       //2.转为JSON
       String jsonString = JSON.toJSONString(brands);

       //3.写数据
       response.setContentType("text/json;charset=utf-8");
       response.getWriter().write(jsonString);
   }

   public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.接收品牌数据
       BufferedReader br = request.getReader();
       String params = br.readLine();//jsonzifc

       //转为Brand对象
       Brand brand = JSON.parseObject(params, Brand.class);

       //2.调用service添加
       brandService.add(brand);

       //3.响应成功的标志
       response.getWriter().write("success");

   }


   //批量删除
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//jsonzifc

        //转为int[]
        int[] ids = JSON.parseObject(params, int[].class);

        //2.调用service添加
        brandService.deleteByIds(ids);

        //3.响应成功的标志
        response.getWriter().write("success");

    }

//分页查询
    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收当前页码和每页显示条数 url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //2.调用service查询
        PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);

        //2.转为JSON
        String jsonString = JSON.toJSONString(pageBean);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

}

  • brand.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="status"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: "#app",

        mounted() {
            //当页面加载完成后,发送异步请求,获取数据
            // var _this = this;
            //
            // axios({
            //     method:"get",
            //     url:"http://localhost:8080/brand-case/selectAllServlet",
            //
            // }).then(function (resp){
            //     _this.tableData = resp.data;
            // })
            this.selectAll();
        },

        methods: {

            //查询所有数据
            selectAll() {
                // var _this = this;
                //
                // axios({
                //     method: "get",
                //     url: "http://localhost:8080/brand-case/brand/selectAll",
                //
                // }).then(function (resp) {
                //     _this.tableData = resp.data;
                // })

                var _this = this;

                axios({
                    method: "get",
                    url: "http://localhost:8080/brand-case/brand/selectByPage?currentPage="+_this.currentPage+"&pageSize="+this.pageSize,

                }).then(function (resp) {
                    //设置表格数据
                    _this.tableData = resp.data.rows; // {rows:[] , totalCount:100}

                    _this.totalCount= resp.data.totalCount;
                })

            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand() {
                var _this = this;
                // console.log(this.brand);
                //发送ajax请求,添加数据
                axios({
                    method: "post",
                    url: "http://localhost:8080/brand-case/brand/add",
                    data: _this.brand
                }).then(function (resp) {
                    if (resp.data == "success") {
                        //添加成功
                        //关闭窗口

                        _this.dialogVisible = false;

                        //然后重新查询
                        _this.selectAll();
                        //提示信息
                        _this.$message({
                            message: '恭喜添加成功',
                            type: 'success'
                        });

                    }
                })

            },

            //分页
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                //重新设置每页显示的条数
                this.pageSize = val;
                this.selectAll();
            },
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                //重新设置当前页码
                this.currentPage = val;
                this.selectAll();
            },

            //完成批量删除
            deleteByIds() {
                //console.log(this.multipleSelection);
                /*
                [
                    {
                        "brandName": "华为",
                        "companyName": "华为技术有限公司",
                        "description": "万物互联",
                        "id": 1,
                        "ordered": 100,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "小米",
                        "companyName": "小米科技有限公司",
                        "description": "are you ok",
                        "id": 2,
                        "ordered": 50,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "格力",
                        "companyName": "格力电器股份有限公司",
                        "description": "让世界爱上中国造",
                        "id": 3,
                        "ordered": 30,
                        "status": 1,
                        "statusStr": "启用"
                    }
                ]
                 */


                //弹出确认提示框
                this.$confirm('此操作将永久删除该文件,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //1.创建id数组[1,2,3] 从this.multipleSelection 获取即可
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = selectionElement.id;

                    }
                    //2.发送AJAX请求
                    var _this = this;

                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteByIds",
                        data: _this.selectedIds
                    }).then(function (resp) {
                        if (resp.data == "success") {
                            //删除成功

                            //然后重新查询
                            _this.selectAll();
                            //提示信息
                            _this.$message({
                                message: '恭喜删除成功',
                                type: 'success'
                            });

                        }
                    })


                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });


            }

        },

        data() {
            return {

                //每页显示的条数
                pageSize:5,

                //总记录数
                totalCount:100,

                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id: "",
                    ordered: "",
                    description: ""
                },
                //被选中的id数组
                selectedIds: [],


                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>

在这里插入图片描述

3.7 条件查询

在这里插入图片描述

3.7.1 后端

在这里插入图片描述

  • BrandMapper.java
package com.itheima.mapper;

import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
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();

    //添加数据
    @Insert("insert into tb_brand value (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    //批量删除
    void deleteByIds(@Param("ids") int[] ids);

    //分页查询
    @Select("select * from tb_brand limit #{begin}, #{size}")
    @ResultMap("brandResultMap")
    List<Brand> selectByPage(@Param("begin") int begin,@Param("size") int size);

    //查询总记录
    @Select("select count(*) from tb_brand")
    int selectTotalCount();

    //条件查询
    List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);

    //根据条件查询总记录
    int selectTotalCountByCondition(Brand brand);
}

  • BrandServiceImpl
package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {

    //1.创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

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

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

        return brands;
    }

    @Override
    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();

    }

    @Override
    public void deleteByIds(int[] ids) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.调用方法
        mapper.deleteByIds(ids);

        sqlSession.commit();

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

    @Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
      //2.获取SqlSesion对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.计算开始索引
        int begin = (currentPage - 1) * pageSize;

        //计算查询条目数
        int size = pageSize;

        //5.查询当前页数据
        List<Brand> rows = mapper.selectByPage(begin,size);
        //6.查询总记录数
        int totalCount = mapper.selectTotalCount();

        //7.封装PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

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

        return pageBean;
    }

    @Override
    public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
        //2.获取SqlSesion对象
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.计算开始索引
        int begin = (currentPage - 1) * pageSize;

        //计算查询条目数
        int size = pageSize;

        //处理brand模糊条件表达式
        String brandName = brand.getBrandName();
        if(brandName != null && brandName.length()>0){
            brand.setBrandName("%"+brandName+"%");
        }

        String companyName = brand.getCompanyName();
        if(companyName != null && companyName.length()>0){
            brand.setCompanyName("%"+companyName+"%");
        }



        //5.查询当前页数据
        List<Brand> rows = mapper.selectByPageAndCondition(begin,size,brand);
        //6.查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(brand);

        //7.封装PageBean对象
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

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

        return pageBean;
    }
}

  • BrandService
package com.itheima.service;

import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;

import java.util.List;

public interface BrandService {

      //查询所有
      List<Brand> selectAll();

      //添加数据
      void add(Brand brand);

      //批量删除
      void deleteByIds( int[] ids);

      //分页查询
      //currentPage:当前页码
      // pageSize:每页展示条数
      PageBean<Brand> selectByPage(int currentPage,int pageSize);

      //条件查询
      PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand);
}

  • BrandServlet
package com.itheima.web.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;


@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
    private BrandService brandService = new BrandServiceImpl();

   public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.调用service查询
       List<Brand> brands = brandService.selectAll();

       //2.转为JSON
       String jsonString = JSON.toJSONString(brands);

       //3.写数据
       response.setContentType("text/json;charset=utf-8");
       response.getWriter().write(jsonString);
   }

   public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
       //1.接收品牌数据
       BufferedReader br = request.getReader();
       String params = br.readLine();//jsonzifc

       //转为Brand对象
       Brand brand = JSON.parseObject(params, Brand.class);

       //2.调用service添加
       brandService.add(brand);

       //3.响应成功的标志
       response.getWriter().write("success");

   }


   //批量删除
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//jsonzifc

        //转为int[]
        int[] ids = JSON.parseObject(params, int[].class);

        //2.调用service添加
        brandService.deleteByIds(ids);

        //3.响应成功的标志
        response.getWriter().write("success");

    }

//分页查询
    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收当前页码和每页显示条数 url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //2.调用service查询
        PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);

        //2.转为JSON
        String jsonString = JSON.toJSONString(pageBean);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    //条件查询
    public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //1.接收当前页码和每页显示条数 url?currentPage=1&pageSize=5
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        //获取查询条件对象
        BufferedReader br = request.getReader();
        String params = br.readLine();//jsonzifc

        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);

        //2.调用service查询
        PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage,pageSize,brand);

        //2.转为JSON
        String jsonString = JSON.toJSONString(pageBean);

        //3.写数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

}

  • BrandMaperr.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!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 property="brandName" column="brand_name" />
        <result property="companyName" column="company_name" />
    </resultMap>


    <delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>


    <select id="selectByPageAndCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        <where>
            <if test="brand.brandName != null and brand.brandName != ''">
                and brand_name like #{brand.brandName}
            </if>
            <if test="brand.companyName != null and brand.companyName != ''">
                and companyName_name like #{brand.companyName}
            </if>
            <if test="brand.status != null">
                and status = #{brand.status}
            </if>

        </where>
        limit #{begin},{size}

    </select>

    <!--     where brand_name = #{brand.brandName},上面要带是因为加了Param-->
    <select id="selectTotalCountByCondition" resultType="java.lang.Integer">
        select count(*)
        from tb_brand
        # 这里把 brand. 去掉
        <where>
            <if test="brandName != null and brandName != '' ">
                and brand_name like #{brandName}
            </if>
            <if test="companyName != null and companyName != ''">
                and companyName_name like #{companyName}
            </if>
            <if test="status != null">
                and status = #{status}
            </if>


        </where>


    </select>


</mapper>

3.7.2 前端

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" :model="brand" class="demo-form-inline">

        <el-form-item label="当前状态">
            <el-select v-model="brand.status" placeholder="当前状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="企业名称">
            <el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
        </el-form-item>

        <el-form-item label="品牌名称">
            <el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
    </el-form>

    <!--按钮-->

    <el-row>

        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>

    </el-row>
    <!--添加数据对话框表单-->
    <el-dialog
            title="编辑品牌"
            :visible.sync="dialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-form-item label="品牌名称">
                <el-input v-model="brand.brandName"></el-input>
            </el-form-item>

            <el-form-item label="企业名称">
                <el-input v-model="brand.companyName"></el-input>
            </el-form-item>

            <el-form-item label="排序">
                <el-input v-model="brand.ordered"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="brand.description"></el-input>
            </el-form-item>

            <el-form-item label="状态">
                <el-switch v-model="brand.status"
                           active-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    type="index"
                    width="50">
            </el-table-column>

            <el-table-column
                    prop="brandName"
                    label="品牌名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="companyName"
                    label="企业名称"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    prop="ordered"
                    align="center"
                    label="排序">
            </el-table-column>
            <el-table-column
                    prop="statusStr"
                    align="center"
                    label="当前状态">
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <el-row>
                    <el-button type="primary">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>

            </el-table-column>

        </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
    </el-pagination>

</div>


<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">

<script src="js/axios-0.18.0.js"></script>

<script>
    new Vue({
        el: "#app",

        mounted(){
            //当页面加载完成后,发送异步请求,获取数据

            this.selectAll();

            /* var _this = this;

             axios({
                 method:"get",
                 url:"http://localhost:8080/brand-case/selectAllServlet"
             }).then(function (resp) {
                 _this.tableData = resp.data;
             })*/

        },

        methods: {

            // 查询分页数据
            selectAll(){
                /* var _this = this;

                 axios({
                     method:"get",
                     url:"http://localhost:8080/brand-case/brand/selectAll"
                 }).then(function (resp) {
                     _this.tableData = resp.data;
                 })*/

                /*
                                var _this = this;

                                axios({
                                    method:"post",
                                    url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
                                    data:this.brand
                                }).then(function (resp) {

                                    //设置表格数据
                                    _this.tableData = resp.data.rows; // {rows:[],totalCount:100}
                                    //设置总记录数
                                    _this.totalCount = resp.data.totalCount;
                                })*/



                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
                    data:this.brand
                }).then(resp =>{
                    //设置表格数据
                    this.tableData = resp.data.rows; // {rows:[],totalCount:100}
                    //设置总记录数
                    this.totalCount = resp.data.totalCount;
                })


            },

            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                // console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                //console.log(this.brand);
                this.selectAll();

            },
            // 添加数据
            addBrand() {
                //console.log(this.brand);
                var _this = this;

                // 发送ajax请求,添加数据
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/add",
                    data:_this.brand
                }).then(function (resp) {
                    if(resp.data == "success"){
                        //添加成功

                        //关闭窗口
                        _this.dialogVisible = false;

                        // 重新查询数据
                        _this.selectAll();
                        // 弹出消息提示
                        _this.$message({
                            message: '恭喜你,添加成功',
                            type: 'success'
                        });

                    }
                })


            },

            //分页
            handleSizeChange(val) {
                //console.log(`每页 ${val} 条`);
                // 重新设置每页显示的条数
                this.pageSize  = val;
                this.selectAll();
            },
            handleCurrentChange(val) {
                //console.log(`当前页: ${val}`);
                // 重新设置当前页码
                this.currentPage  = val;
                this.selectAll();
            },

            // 批量删除
            deleteByIds(){


                //console.log(this.multipleSelection);
                /*
                [
                    {
                        "brandName": "华为",
                        "companyName": "华为技术有限公司",
                        "description": "万物互联",
                        "id": 1,
                        "ordered": 100,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "小米",
                        "companyName": "小米科技有限公司",
                        "description": "are you ok",
                        "id": 2,
                        "ordered": 50,
                        "status": 1,
                        "statusStr": "启用"
                    },
                    {
                        "brandName": "格力",
                        "companyName": "格力电器股份有限公司",
                        "description": "让世界爱上中国造",
                        "id": 3,
                        "ordered": 30,
                        "status": 1,
                        "statusStr": "启用"
                    }
                ]
                 */

                // 弹出确认提示框

                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮

                    //1. 创建id数组 [1,2,3], 从 this.multipleSelection 获取即可
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = selectionElement.id;

                    }

                    //2. 发送AJAX请求
                    var _this = this;

                    // 发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteByIds",
                        data:_this.selectedIds
                    }).then(function (resp) {
                        if(resp.data == "success"){
                            //删除成功

                            // 重新查询数据
                            _this.selectAll();
                            // 弹出消息提示
                            _this.$message({
                                message: '恭喜你,删除成功',
                                type: 'success'
                            });

                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮

                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });




            }

        },
        data() {
            return {
                // 每页显示的条数
                pageSize:5,
                // 总记录数
                totalCount:100,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id: "",
                    ordered: "",
                    description: ""
                },
                // 被选中的id数组
                selectedIds:[],
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }, {
                    brandName: '华为',
                    companyName: '华为科技有限公司',
                    ordered: '100',
                    status: "1"
                }]
            }
        }
    })

</script>

</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/892182.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

京东API简介及应用实例

京东API&#xff08;Application Programming Interface&#xff09;&#xff0c;即京东开放平台的接口&#xff0c;是京东提供给开发者的一组规定格式和约定的接口&#xff0c;用于实现与京东电商平台进行数据交互和功能调用。通过使用京东API&#xff0c;开发者可以实现商品查…

Unity的TimeScale的影响范围分析

大家好&#xff0c;我是阿赵。 这期来说一下Unity的TimeScale。 一、前言 Unity提供了Time这个类&#xff0c;来控制时间。其实我自己倒是很少使用这个Time&#xff0c;因为做网络同步的游戏&#xff0c;一般是需要同步服务器时间&#xff0c;所以我比较多是在使用System.Date…

【运筹优化】贪心启发式算法和蜘蛛猴优化算法求解连续选址问题 + Java代码实现

文章目录 一、问题描述二、思路分析三、解决方案3.1 贪心启发式算法3.2 群体智能算法&#xff08;蜘蛛猴优化算法&#xff09; 四、总结 一、问题描述 选址问题是指在规划区域里选择一个或多个设施的位置&#xff0c;使得目标最优。 按照规划区域的结构划分&#xff0c;可以将…

QT的network的使用

一个简单的双向的网络连接和信息发送。效果如下图所示&#xff1a; 只需要配置这个主机的IP和端口号&#xff0c;由客户端发送链接请求。即可进行连接。 QT的network模块是一个用于网络编程的模块&#xff0c;它提供了一系列的类和函数&#xff0c;可以让您使用TCP/IP协议来创…

pdf格式文件下载不预览,云存储的跨域解决

需求背景 后端接口中返回的是pdf文件路径比如&#xff1a; pdf文件路径 &#xff08;https://wangzhendongsky.oss-cn-beijing.aliyuncs.com/wzd-test.pdf&#xff09; 前端适配是这样的 <ahref"https://wangzhendongsky.oss-cn-beijing.aliyuncs.com/wzd-test.pdf&…

Spring框架之AOP详解

目录 一、前言 1.1.Spring简介 1.2.使用Spring的优点 二、Spring之AOP详解 2.1.什么是AOP 2.2.AOP在Spring的作用 2.3.AOP案例讲解 三、AOP案例实操 3.0.代理小故事&#xff08;方便理解代理模式&#xff09; 3.1.代码演示 3.2.前置通知 3.3.后置通知 3.3.环绕通知…

聚观早报|俞敏洪东方甄选带货北京特产;京东物流上半年盈利

【聚观365】8月17日消息 俞敏洪东方甄选直播间带货北京特产 京东物流上半年实现盈利 百度CTO称大语言模型为人工智能带来曙光 腾讯控股第二季度盈利262亿元 2023中国家庭智慧大屏消费白皮书 俞敏洪东方甄选直播间带货北京特产 近日&#xff0c;东方甄选在北京平谷区开播&…

Linux:shell脚本:基础使用(5)《正则表达式-sed工具》

sed是一种流编辑器&#xff0c;它是文本处理中非常中的工具&#xff0c;能够完美的配合正则表达式使用&#xff0c;功能不同凡响。 处理时&#xff0c;把当前处理的行存储在临时缓冲区中&#xff0c;称为“模式空间”&#xff08;pattern space&#xff09;&#xff0c;接着用s…

数据库MySQL 创建表INSERT

创建表 常见数据类型(列类型) 列类型之整型 unsigned的用法 列类型之bit 二进制表示 bit&#xff08;8&#xff09;表示一个字节 列类型之小数 1.单精度float 双精度double 2.decimal 自定义 M为小数点前面有多少位 D是小数点后面有多少位 列类型之字符串 1.char( 字符 )…

实现简单的element-table的拖拽效果

第一步&#xff0c;先随便创建element表格 <el-table ref"dragTable" :data"tableData" style"width: 100%" border fit highlight-current-row><el-table-column label"日期" width"180"><template slot-sc…

element-Plus中el-menu菜单无法正常收缩解决方案

<el-menu :collapse"true">如图所示收缩之后&#xff0c;有子级的菜单还有箭头文字显示 从代码对比看层级就不太对了&#xff0c;嵌套错误了&#xff0c;正常下方官网的ul标签下直接是li&#xff0c;在自己的代码中&#xff0c;ul标签下是div标签&#xff0c;层…

爬虫工具的选择与使用:阐述Python爬虫优劣势

作为专业爬虫ip方案解决服务商&#xff0c;我们每天都面对着大量的数据采集任务需求。在众多的爬虫工具中&#xff0c;Python爬虫凭借其灵活性和功能强大而备受青睐。本文将为大家分享Python爬虫在市场上的优势与劣势&#xff0c;帮助你在爬虫业务中脱颖而出。 一、优势篇 灵活…

初试rabbitmq

rabbitmq的七种模式 Hello word 客户端引入依赖 <!--rabbitmq 依赖客户端--><dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>5.8.0</version></dependency> 生产者 imp…

相对于多进程,你真的知道为什么要使用多线程吗(C/C++多线程编程)

目录 前言 线程VS进程 POSIX线程库的使用 线程创建 线程等待 线程分离 线程状态 可结合态线程实例 分离态线程实例 线程退出 线程的同步与互斥 同步互斥的概念 互斥锁&#xff08;互斥&#xff09; 互斥锁的使用步骤 总结说明 信号量 信号量的使用步骤 条件变…

数据包如何游走于 Iptables 规则之间?

在前文《Linux路由三大件》中&#xff0c;我们提到了 iptables 可以修改数据包的特征从而影响其路由。这个功能无论是传统场景下的 防火墙&#xff0c;还是云原生场景下的 服务路由&#xff08;k8s service&#xff09;、网络策略(calico network policy) 等都有依赖。 虽然业…

7.逻辑结构VS物理结构

第四章 文件管理 7.逻辑结构VS物理结构 ​   fopen这个函数做的事情就是打开了“test.txt”这个文件&#xff0c;并且“w”说明是以“写”的方式打开的&#xff0c;以“写”的方式打开才能往这个文件里写入数据&#xff0c;如果文件打开了那么fp这个指针就可以指向和这个文件…

Eclipse如何设置快捷键

在eclopse设置注释行和取消注释行 // 打开eclipse&#xff0c;依次打开&#xff1a;Window -> Preferences -> General -> Key&#xff0c;

数据结构--关键路径

数据结构–关键路径 AOE⽹ 在 带权有向图 \color{red}带权有向图 带权有向图中&#xff0c;以 顶点表示事件 \color{red}顶点表示事件 顶点表示事件&#xff0c;以 有向边表示活动 \color{red}有向边表示活动 有向边表示活动&#xff0c;以 边上的权值表示完成该活动的开销 \…

HCIE--------------------------------------第一节OSPF快速收敛(OSPF与BGP联动)

一、OSPF快速收敛概述 OSPF快速收敛是为了提高路由的收敛速度而做的扩展特性&#xff0c;包括&#xff1a;PRC&#xff08;Partial Route Calculation&#xff0c;部分路由计算&#xff09;和智能定时器。 同时&#xff0c;OSPF支持故障恢复快速收敛&#xff0c;例如通过OSPF …

Linux Server 20.04 Qt5.14.2配置Jetson Orin Nano Developer Kit 交叉编译环境

最近公司给了我一块Jetson Orin Nano的板子&#xff0c;让我搭建交叉编译环境&#xff0c;所以有了下面的文章 一 :Qt5.14.2交叉编译环境安装 1.准备 1.1设备环境 1.1.1 Server: Ubuntu20.04: Qt 源码 5.14.2 Qt 软件 5.14.2 gcc 版本 9.4.0 g 版本 9.4.0 1.1.2 Jetson …