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 快速入门
- 新建HTML页面,引入 Vue.js文件
<script src="js/vue.js"></script>
- 在JS代码区域,创建Vue核心对象,进行数据绑定
new Vue({
el: "#app",
data() {
return {
username: ""
}
}
});
- 编写视图
<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快速入门
- 引入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">
- 创建Vue核心对象
<script>
new Vue({
el:"#app"
})
</script>
- 官网复制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中有两种布局方式:
-
Layout布局:通过基础的24分栏,迅速简便地创建布局
-
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>