效果图如下:
项目依赖:
1.mysql驱动包
2.junit用来测试
3.mybatis
4.javax.servlet
5.fastjson用来进行数据转换
准备对象去实现对数据库数据的表现
package cn.itaxu.pojo;
/**
* @Description: cn.itaxu.pojo
* @author: Axu
* @date:2022/11/2 22:28
*/
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Brand() {
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
// 逻辑视图
public 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 +
'}';
}
}
PageBean用来实现分页查询的表现
import java.util.List;
/**
* 分页查询的JavaBean
* @Description: cn.itaxu.pojo
* @author: Axu
* @date:2022/11/7 11:00
*/
public class PageBean<T> {
// 总记录数
private int totalCount;
// 当前页数据
private List<T> rows;
public PageBean() {
}
public PageBean(int totalCount, List<T> rows) {
this.totalCount = totalCount;
this.rows = 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;
}
@Override
public String toString() {
return "PageBean{" +
"totalCount=" + totalCount +
", rows=" + rows +
'}';
}
}
对应的增删改查接口
package cn.itaxu.mapper;
import cn.itaxu.pojo.Brand;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @Description: cn.itaxu.mapper
* @author: Axu
* @date:2022/11/4 20:57
*/
public interface BrandMapper {
/**
* 查询所有
* @return
*/
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
/**
* 添加数据
* @param brand
* @return
*/
@Insert("insert into tb_brand values(#{id},#{brandName},#{companyName}," +
"#{ordered},#{description},#{status})")
void add(Brand brand);
/**
* 批量删除
* @param ids
* @return
*/
void deleteByIds(@Param("ids") int[] ids);
/**
* 更新数据
* @param brand
*/
@Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered}," +
"brand_info=#{description},status=#{status} where id=#{id}")
void update(Brand brand);
/**
*分页查询
* @param begin
* @param size
* @return
*/
@Select("select * from tb_brand limit #{begin} , #{size}")
@ResultMap("brandResultMap")
List<Brand> selectByPage(@Param("begin") int begin,@Param("size") int size);
/**
* 总记录条数
* @return
*/
@Select("select count(*) from tb_brand")
int selectTotalCount();
/**
* 动态 SQL 查询数据
* @param begin
* @param size
* @param brand
* @return
*/
List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);
/**
* 根据条件查询总记录数
* @param brand
* @return
*/
int selectTotalCountByCondition(Brand brand);
/**
* 回显数据
* @param id
* @return
*/
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
/**
* 删除单条数据
* @param id
*/
@Delete("delete from tb_brand where id=#{id}")
void deleteById(int id);
}
业务层接口(降低耦合度)
package cn.itaxu.service;
import cn.itaxu.pojo.Brand;
import cn.itaxu.pojo.PageBean;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @Description: cn.itaxu.service
* @author: Axu
* @date:2022/11/6 22:45
*/
public interface BrandService {
/**
* 查询所有品牌
* @return
*/
List<Brand> selectAll();
/**
* 添加数据
*/
void add(Brand brand);
/**
* 批量删除
* @param ids
*/
void deleteByIds(int[] ids);
/**
* 分页查询
* @param currentPage 当前页码
* @param pageSize 每页显示条数
* @return
*/
PageBean<Brand> selectByPage(int currentPage,int pageSize);
/**
* 分页条件查询
* @param currentPage
* @param pageSize
* @param brand
* @return
*/
PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand);
/**
* 回显数据
* @param id
* @return
*/
Brand selectById(int id);
/**
* 更新数据
* @param brand
*/
void update(Brand brand);
/**
* 删除单条数据
* @param id
*/
void deleteById(int id);
}
业务层接口实现类
package cn.itaxu.service.impl;
import cn.itaxu.mapper.BrandMapper;
import cn.itaxu.pojo.Brand;
import cn.itaxu.pojo.PageBean;
import cn.itaxu.service.BrandService;
import cn.itaxu.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
/**
* @Description: cn.itaxu.service.impl
* @author: Axu
* @date:2022/11/6 22:45
*/
public class BrandServiceImpl implements BrandService {
private SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
/**
* 查询所有品牌数据
* @return
*/
@Override
public List<Brand> selectAll() {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectAll();
sqlSession.close();
return brands;
}
/**
* 添加数据
* @param brand
*/
@Override
public void add(Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
/**
* 根据 ids 批量删除
* @param ids
*/
@Override
public void deleteByIds(int[] ids) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteByIds(ids);
sqlSession.commit();
sqlSession.close();
}
/**
* 分页查询
* @param currentPage 当前页码
* @param pageSize 每页显示条数
* @return
*/
@Override
public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 计算开始索引
int begin = (currentPage-1) * pageSize;
// 计算条目数
int size = pageSize;
// 查询当前页数据
List<Brand> rows = mapper.selectByPage(begin, size);
// 查询总记录数
int totalCount = mapper.selectTotalCount();
// 封装pageBean对象
PageBean<Brand> pageBean = new PageBean<Brand>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
// 释放资源
sqlSession.close();
return pageBean;
}
/**
* 条件分页查询
* @param currentPage
* @param pageSize
* @param brand
* @return
*/
@Override
public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 计算开始索引
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+"%");
}
// 查询当前页数据
List<Brand> rows = mapper.selectByPageAndCondition(begin, size, brand);
// 查询总记录
int totalCount = mapper.selectTotalCountByCondition(brand);
// 封装PageBean对象
PageBean<Brand> brandBean = new PageBean<Brand>();
brandBean.setRows(rows);
brandBean.setTotalCount(totalCount);
// 释放资源
sqlSession.close();
return brandBean;
}
/**
* 根据 id 查询
* @param id
* @return
*/
@Override
public Brand selectById(int id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand brand = mapper.selectById(id);
sqlSession.close();
return brand;
}
/**
* 更新数据
* @param brand
*/
@Override
public void update(Brand brand) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
Brand b = mapper.selectById(brand.getId());
if (b!=null){
mapper.update(brand);
}
sqlSession.commit();
sqlSession.close();
}
/**
* 根据 id 删除单条数据
* @param id
*/
@Override
public void deleteById(int id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
}
实现复杂sql语句的xml配置文件
<mapper namespace="cn.itaxu.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result property="brandName" column="brand_name"></result>
<result property="companyName" column="company_name"></result>
<result property="description" column="brand_info"></result>
</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 company_name like #{brand.companyName}
</if>
<if test="brand.status != null">
and status=#{brand.status}
</if>
</where>
limit #{begin} , #{size}
</select>
<select id="selectTotalCountByCondition" resultType="java.lang.Integer">
select count(*) from tb_brand
<where>
<if test="brandName != null and brandName != ''">
and brand_name like #{brandName}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="status != null">
and status=#{status}
</if>
</where>
</select>
</mapper>
#前端代码
<div id="app">
<!-- 导航菜单-->
<el-menu
:default-active="activeIndex2"
class="el-menu-demo"
mode="horizontal"
@select="handleSelect"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<template>
<h3 align="center"><img src="./img/E-commerce.png" width="50" height="50" align="center">
电商后台数据模型
</h3>
</template>
<el-menu-item index="1">处理中心</el-menu-item>
<el-submenu index="2">
<template slot="title">我的工作台</template>
<el-menu-item index="2-1">后台品牌模型</el-menu-item>
</el-submenu>
<el-menu-item index="3" disabled>消息中心</el-menu-item>
<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item>
</el-menu>
<!-- 搜索表单-->
<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 style="margin-left: 20%">
<el-button type="danger" plain @click="deleteBrandByIds">批量删除</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="cancelAdd">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<!-- 修改数据的对话框表单-->
<el-dialog
title="修改数据"
:visible.sync="updateDialogVisible"
width="30%">
<el-form ref="form" :model="update" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model="update.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="update.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model="update.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model="update.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="update.status"
active-value="1"
inactive-value="0">
</el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="updateBrand">提交</el-button>
<el-button @click="cancel">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<h4 align="center"><img src="./img/product.png" width="50" height="50" align="center"><font color="gray">产品列表
</font></h4>
<!-- 表格-->
<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"
label="排序"
align="center"
>
</el-table-column>
<el-table-column
prop="description"
label="备注"
align="center"
>
</el-table-column>
<el-table-column
prop="statusStr"
label="当前状态"
align="center"
>
</el-table-column>
<el-table-column
prop="address"
label="操作"
align="center"
>
<el-row>
<el-button type="primary" @click="modify">修改</el-button>
<el-button type="danger" @click="deleteById">删除</el-button>
</el-row>
</el-table-column>
</el-table>
</template>
<!-- 分页工具条-->
<div class="block">
<el-pagination
@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="totalCount">
</el-pagination>
</div>
需要引入的外部文件
<script src="https://cdn.staticfile.org/axios/1.1.3/axios.js"></script>
<script src="./js/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
整体javascript逻辑代码
<script>
new Vue({
el:"#app",
mounted(){
//当页面加载完毕后,发送异步请求
this.selectAll();
},
methods: {
// 查询所有品牌数据
selectAll(){
axios({
method:'post',
url:`http://localhost:8080/brand/selectByPageAndCondition?currentPage=${this.currentPage}&pageSize=${this.pageSize}`,
data:this.brand
}).then(resp=>{
this.tableData = resp.data.rows;
this.totalCount = resp.data.totalCount;
})
},
cancelAdd(){
this.dialogVisible = false;
// 用户点击了取消按钮
this.$message({
showClose: true,
message: '您取消了添加数据!',
center:true
});
},
modify(){
for (let i = 0; i < this.multipleSelection.length; i++) {
var selectionElement = this.multipleSelection[i];
this.update.id = selectionElement.id;
}
if (this.update.id == '' || this.update.id == null){
this.$message({
showClose: true,
message: '请选中您要修改的数据!',
type: 'error',
center:true,
});
return;
}
axios({
method:'post',
url:'http://localhost:8080/brand/selectById',
data:this.update.id,
}).then(resp=>{
this.update = resp.data;
this.updateDialogVisible = true;
})
},
cancel(){
this.updateDialogVisible = false;
this.$message({
showClose: true,
message: '您已取消修改',
center:true
});
},
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() {
this.selectAll();
},
// 添加数据
addBrand(){
axios({
method: 'post',
url: 'http://localhost:8080/brand/add',
data:this.brand,
}).then( (resp) => {
if (resp.data=="success"){
// 关闭添加数据对话框表单
this.dialogVisible = false;
// 重新查询数据
this.selectAll();
// 弹出提示信息
this.$message({
message: '添加数据成功!',
type: 'success',
center: true
});
}
})
},
// 更新数据
updateBrand(){
axios({
method:'post',
url:'http://localhost:8080/brand/update',
data:this.update,
}).then(resp=>{
if (resp.data=="success"){
this.updateDialogVisible = false;
this.selectAll();
this.$message({
showClose: true,
message: '更新数据成功!',
type: 'success',
center:true
});
}
})
},
// 批量删除
deleteBrandByIds(){
// 弹出确认提示框
this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 1.创建id数组,从this.multipleSelection中获取
for (let i = 0; i < this.multipleSelection.length; i++) {
let selectionElement = this.multipleSelection[i];
this.selectedIds[i] = selectionElement.id
}
if (this.selectedIds.length < 1){
this.$message({
showClose: true,
message: '请选中您要删除的数据!',
type: 'error',
center:true,
});
return;
}
// 2.发送ajax请求
axios({
method: 'post',
url: 'http://localhost:8080/brand/deleteByIds',
data:this.selectedIds,
}).then( (resp) => {
if (resp.data=="success"){
// 重新查询数据
this.selectAll();
// 弹出提示信息
this.$message({
message: '删除数据成功!',
type: 'success',
center: true
});
}
});
}).catch(() => {
// 用户点击取消按钮
this.$message({
type: 'info',
message: '您已取消删除',
center:true
});
});
// 清除数组
this.selectedIds = [];
},
// 删除单条数据
deleteById(){
for (let i = 0; i < this.multipleSelection.length; i++) {
var selectionElement = this.multipleSelection[i];
this.selectedId = selectionElement.id;
}
if (this.selectedId == '' || this.selectedId == null){
this.$message({
showClose: true,
message: '请选中您要删除的数据!',
type: 'error',
center:true,
});
return;
}
axios.post("http://localhost:8080/brand/deleteById",this.selectedId)
.then(resp=>{
if (resp.data == "success"){
this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 重新查询数据
this.selectAll();
this.$message({
type: 'success',
message: '删除成功!',
center:true
});
}).catch(() => {
this.$message({
type: 'info',
message: '您已取消删除',
center:true,
});
});
}
});
// 清空selectedId
this.selectedId = ''
},
// 分页
handleSizeChange(val) {
// 重新设置每页显示条数
this.pageSize = val;
this.selectAll();
},
handleCurrentChange(val) {
// 重新设置当前页码
this.currentPage = val;
this.selectAll();
}
},
data() {
return {
// 被选中的单个id
selectedId:'',
// 总记录条数
totalCount:'',
// 每页显示条数
pageSize:10,
// 修改数据表单显示状态
updateDialogVisible:false,
// 当前页码
currentPage:1,
// 控制添加数据对话框表单是否显示
dialogVisible: false,
// 品牌模型数据
brand: {
companyName: '',
status: '',
brandName:'',
id:'',
ordered:'',
description:'',
},
// 更新模型数据
update: {
companyName: '',
status: '',
brandName:'',
id:'',
ordered:'',
description:'',
},
// 复选框选中数据集合
multipleSelection:[],
// 被选中的id数组
selectedIds:[],
// 表格数据
tableData: []
}
},
})
</script>
#后台代码
基类(大大简化了开发效率,不需要创建多个功能类,它是管理所有功能的基类)
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;
/**
* 替换HttpServlet,根据请求的最后一段路径来进行方法分发
* @Description: cn.itaxu.web.servlet
* @author: Axu
* @date:2022/11/7 9:02
*/
public class BaseServlet extends HttpServlet {
// 根据请求的最后一段路径来进行方法分发
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取请求路径
String uri = req.getRequestURI(); // /brand/selectAll
// 2.获取最后一段路径
int index = uri.lastIndexOf("/");
String methodName = uri.substring(index+1);
// 3.执行方法
// 3.1 获取BrandServlet 字节码对象 Class
// 这里的this 代表 BrandServlet,谁调用我,我代表谁
Class<? extends BaseServlet> cls = this.getClass();
// 3.2 获取方法的Method对象
try {
Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 3.3 执行方法
method.invoke(this, req, resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
业务层的功能实现类
import cn.itaxu.pojo.Brand;
import cn.itaxu.pojo.PageBean;
import cn.itaxu.service.BrandService;
import cn.itaxu.service.impl.BrandServiceImpl;
import com.alibaba.fastjson.JSON;
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;
/**
* @Description: cn.itaxu.web.servlet
* @author: Axu
* @date:2022/11/7 9:06
*/
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet {
private BrandService service = new BrandServiceImpl();
/**
* 查询所有
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.调用BrandService完成查询
List<Brand> brands = service.selectAll();
// 2.将集合转为JSON数据
String s = JSON.toJSONString(brands);
// 3.响应数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
/**
* 添加数据
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// 1.获取请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 2.将JSON字符串转为Java对象
Brand brand = JSON.parseObject(params, Brand.class);
// 3.调用service
service.add(brand);
// 4.响应成功标识
response.getWriter().write("success");
}
/**
* 批量删除
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决POST请求中文乱码
request.setCharacterEncoding("UTF-8");
// 1.接收数据 [1,2,3]
BufferedReader br = request.getReader();
String params = br.readLine();
// 2.将JSON数据转为 int 数组
int[] ids = JSON.parseObject(params, int[].class);
// 3.调用service
service.deleteByIds(ids);
// 4.响应成功标识
response.getWriter().write("success");
}
/**
* 分页查询
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
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");
// 2.调用service
PageBean<Brand> brandBean = service.selectByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
// 3.将集合转为JSON数据
String s = JSON.toJSONString(brandBean);
// 4.响应数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
/**
* 分页条件查询
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 解决POST请求乱码问题
request.setCharacterEncoding("UTF-8");
// 1.接收当前页码 和 每页显示条数 url?currentPage=1&pageSize=5
String currentPage = request.getParameter("currentPage");
String pageSize = request.getParameter("pageSize");
// 获取查询条件对象
BufferedReader br = request.getReader();
String params = br.readLine();
// 2.将JSON数据转为Java对象
Brand brand = JSON.parseObject(params, Brand.class);
// 3.调用service
PageBean<Brand> brandBean = service.selectByPageAndCondition(Integer.parseInt(currentPage),
Integer.parseInt(pageSize),brand);
// 4.将集合转为JSON数据
String s = JSON.toJSONString(brandBean);
// 5.响应数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
/**
* 回显数据
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectById(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 接收表单的id
BufferedReader br = request.getReader();
String _id = br.readLine();
// 将JSON数据转为int数据
Integer id = JSON.parseObject(_id, int.class);
// 调用service
Brand brand = service.selectById(id);
// 将Java对象转为JSON数据
String s = JSON.toJSONString(brand);
// 响应数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(s);
}
/**
* 更新数据
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 解决POST请求中文乱码问题
request.setCharacterEncoding("UTF-8");
// 接收请求体数据
BufferedReader br = request.getReader();
String s = br.readLine();
// 把JSON数据转为Java对象
Brand brand = JSON.parseObject(s, Brand.class);
// 调用service
service.update(brand);
// 响应成功标识
response.getWriter().write("success");
}
public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决POST请求中文乱码
request.setCharacterEncoding("UTF-8");
// 1.接收请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 2.将JSON数据转为 int 数据
int id = JSON.parseObject(params, int.class);
// 3.调用service
service.deleteById(id);
// 4.响应成功标识
response.getWriter().write("success");
}
}