JavaWeb综合案例
JavaWeb综合案例
笔记目录:(https://www.cnblogs.com/wenjie2000/p/16378441.html)
视频教程(P154~P163)
-
功能列表
环境搭建
-
执行提供的下面的tb_brand.sql脚本
-- 删除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;
-
在idea中创建基本的JavaWeb模块(前端页面就是上一节最后的成品。基本结构的代码可以直接复制之前笔记的brand项目部分的后端代码内容,因为是以学习为目的,个人还是建议从头开始敲,想不起来的再看之前的笔记)
1.查询所有
2.新增品牌
Servlet代码优化
Web 层的Servlet个数太多了,不利于管理和编写
将Servlet进行归类,对于同一个实体的操作方法,写到一个Servlet中。比如: BrandServlet、
UserServlet(需要用到反射的知识)
3.修改品牌
后台代码和新增品牌类似
4.删除品牌
后台代码和新增品牌类似
5.批量删除
6.分页查询
select * from tb_brand limit 0,5;-- 从第1条开始查,查5条
页面传递的参数:当前页码、每页显示条数
参数1:开始索引=(当前页码-1)*每页显示条数
参数2:查询的条目数=每页显示条数
有两种数据,ajax只能一次性接收数据,两种数据需要后端同时发给前端,必须将两种数据封装到一起。又需要将数据转成json,所以只能创建新的Bean类来建立对象。
7.条件查询
- 3个条件之间什么关系? AND
- 3个条件必须全部填写吗? 不需要→动态SQL<if> <where>
- 条件查询需要带分页吗? 需要
前端代码优化
之前的代码需要用到var _this=this;
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(response){
//设置表格数据
_this.tableData = response.data.rows;//{"rows":[],"totalCount":52}
//设置总记录数
_this.totalCount = response.data.totalCount;
})
可以改成以下方式,就不需要定义_this
来获取data()
中的数据了
axios({
method: "post",
url: "http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
data:this.brand,
}).then(response =>{
//设置表格数据
this.tableData = response.data.rows;//{"rows":[],"totalCount":52}
//设置总记录数
this.totalCount = response.data.totalCount;
})
完整代码
文件结构
代码
brand-case
src/main
java
com.itwen
mapper
BrandMapper.java
package com.itwen.mapper; import com.itwen.pojo.Brand; import org.apache.ibatis.annotations.*; import java.util.List; public interface BrandMapper { /** * 查询所有 * @return */ @Select("select * from tb_brand") @ResultMap("brandResultMap") List<Brand> selectAll(); /** * 添加数据 * @param brand */ @Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})") void add(Brand brand); /** * 修改数据 * @param brand */ @Update("UPDATE tb_brand SET brand_name= #{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} WHERE id=#{id}") void update(Brand brand); /** * 删除数据 * @param id */ @Delete("delete from tb_brand where id=#{id}") void deleteById(int id); /** * 批量删除 * @param ids */ void deleteByIds(@Param("ids") int[] ids); /** * 分页查询 * @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(); /** * 分页条件查询 * @param begin * @param size * @param brand * @return */ List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand); /** * 查询总记录数 * @return */ int selectTotalCountByCondition(Brand brand); }
pojo
Brand.java
package com.itwen.pojo; public class Brand { private Integer id; private String brandName; private String companyName; private Integer ordered; private String description; private Integer status; public String getStatusStr(){ if (status==null){ return "未知"; } return status==0? "禁用":"启用"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Integer getOrdered() { return ordered; } public void setOrdered(Integer ordered) { this.ordered = ordered; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
PageBean.java
package com.itwen.pojo; import java.util.List; public class PageBean<T> { //总记录数 private int totalCount; //当前页数据 private List<T> rows;//限制数据类型是为了防止存入的数据类型不一致,不使用<Brand>使用<T>是考虑到以后可能不只是用来存储Brand数组,例如查询用户列表 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; } }
service
impl
BrandServiceImpl.java
package com.itwen.service.impl; import com.itwen.mapper.BrandMapper; import com.itwen.pojo.Brand; import com.itwen.pojo.PageBean; import com.itwen.service.BrandService; import com.itwen.util.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List; public class BrandServiceImpl implements BrandService { //创建sqlSessionFactory工厂对象 SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory(); public List<Brand> selectAll(){ //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 List<Brand> brands = mapper.selectAll(); //释放资源 sqlSession.close(); return brands; } @Override public void add(Brand brand) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 mapper.add(brand); sqlSession.commit();//提交事务 //释放资源 sqlSession.close(); } @Override public void update(Brand brand) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 mapper.update(brand); sqlSession.commit();//提交事务 //释放资源 sqlSession.close(); } @Override public void deleteById(int id) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 mapper.deleteById(id); sqlSession.commit();//提交事务 //释放资源 sqlSession.close(); } @Override public void deleteByIds(int[] ids) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 mapper.deleteByIds(ids); sqlSession.commit();//提交事务 //释放资源 sqlSession.close(); } @Override public PageBean<Brand> selectByPage(int currentPage, int pageSize) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //调用方法 int totalCount = mapper.selectTotalCount();//总记录数 int begin=(currentPage-1)*pageSize; List<Brand> brands = mapper.selectByPage(begin, pageSize);//当前页数据 //封装 PageBean<Brand> pageBean = new PageBean<>(); pageBean.setTotalCount(totalCount); pageBean.setRows(brands); //释放资源 sqlSession.close(); return pageBean; } @Override public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) { //获取sqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //获取BrandMapper BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); //模糊查询,需要加上%(不能在写sql语句部分加,会出问题。例如: like %‘华为’%) 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+"%"); } //调用方法 int totalCount = mapper.selectTotalCountByCondition(brand);//总记录数 int begin=(currentPage-1)*pageSize; List<Brand> brands = mapper.selectByPageAndCondition(begin, pageSize,brand);//当前页数据 //封装 PageBean<Brand> pageBean = new PageBean<>(); pageBean.setTotalCount(totalCount); pageBean.setRows(brands); //释放资源 sqlSession.close(); return pageBean; } }
BrandService.java
package com.itwen.service; import com.itwen.pojo.Brand; import com.itwen.pojo.PageBean; import java.util.List; //这里service使用接口是为了降低与servlet的耦合度,目前展示没多大用,以后学了sping就懂了 public interface BrandService { /** * 查询所有 * @return */ List<Brand> selectAll(); /** * 添加数据 * @param brand */ void add(Brand brand); /** * 修改数据 * @param brand */ void update(Brand brand); /** * 删除数据 * @param id */ void deleteById(int id); /** * 批量删除 * @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); }
util
SqlSessionFactoryUtils.java
package com.itwen.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; } }
web.servlet
BaseServlet.java
package com.itwen.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 { //获取请求路径 String uri = req.getRequestURI();// brand-case/brand/selectAll // System.out.println(uri); //获取最后一段路径(也是方法名) int index = uri.lastIndexOf("/"); String methodName = uri.substring(index+1);// /selectAll // System.out.println(methodName); Class<? extends BaseServlet> cls = this.getClass();//获取当前类 //获取方法Method对象 try { Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); method.invoke(this,req,resp); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
BrandServlet.java
package com.itwen.web.servlet; import com.alibaba.fastjson.JSON; import com.itwen.pojo.Brand; import com.itwen.pojo.PageBean; import com.itwen.service.BrandService; import com.itwen.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(); /** * 查询所有 * @param req * @param resp * @throws ServletException * @throws IOException */ public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //调用service查询 List<Brand> brands = brandService.selectAll(); //数据转为json String jsonString = JSON.toJSONString(brands); //写数据 resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } /** * 添加品牌 * @param req * @param resp * @throws ServletException * @throws IOException */ public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8");//如果post的数据乱码,加上这句 //接收品牌数据 BufferedReader br = req.getReader(); String params = br.readLine(); //转为Brand对象 Brand brand = JSON.parseObject(params, Brand.class); //调用service添加 brandService.add(brand); //响应成功标识 resp.getWriter().write("success"); } /** * 修改信息 * @param req * @param resp * @throws ServletException * @throws IOException */ public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8");//如果post的数据乱码,加上这句 //接收品牌数据 BufferedReader br = req.getReader(); String params = br.readLine(); //转为Brand对象 Brand brand = JSON.parseObject(params, Brand.class); //调用service添加 brandService.update(brand); //响应成功标识 resp.getWriter().write("success"); } public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8");//如果post的数据乱码,加上这句 //接收品牌数据 BufferedReader br = req.getReader(); String params = br.readLine(); //转为 int int id = JSON.parseObject(params, int.class);//fastjson也可以用来字符串转数组 //调用services批量删除 brandService.deleteById(id); //响应成功标识 resp.getWriter().write("success"); } /** * 批量删除品牌 * @param req * @param resp * @throws ServletException * @throws IOException */ public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8");//如果post的数据乱码,加上这句 //接收品牌数据 BufferedReader br = req.getReader(); String params = br.readLine(); //转为 int[] int[] ids = JSON.parseObject(params, int[].class);//fastjson也可以用来字符串转数组 //调用services批量删除 brandService.deleteByIds(ids); //响应成功标识 resp.getWriter().write("success"); } /** * 分页查询 * @param req * @param resp * @throws ServletException * @throws IOException */ public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收数据 当前页码和每页条数 url?currentPage=1&pageSize=5 String _currentPage = req.getParameter("currentPage"); String _pageSize = req.getParameter("pageSize"); int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); //调用service查询 PageBean<Brand> brandPageBean = brandService.selectByPage(currentPage, pageSize); //数据转为json String jsonString = JSON.toJSONString(brandPageBean); //写数据 resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } public void selectByPageAndCondition(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收数据 当前页码和每页条数 url?currentPage=1&pageSize=5 String _currentPage = req.getParameter("currentPage"); String _pageSize = req.getParameter("pageSize"); int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); req.setCharacterEncoding("UTF-8");//如果post的数据乱码,加上这句 //接收品牌数据 BufferedReader br = req.getReader(); String params = br.readLine(); //转为Brand对象 Brand brand = JSON.parseObject(params, Brand.class); //调用service查询 PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize,brand); //数据转为json String jsonString = JSON.toJSONString(pageBean); //写数据 resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } }
resources
com.itwen.mapper
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.itwen.mapper.BrandMapper"> <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName"></result> <result column="company_name" property="companyName"></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>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--起别名--> <typeAliases> <package name="com.itwen.pojo"/> </typeAliases> <!--设置连接数据库的环境--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db1"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!--引入映射文件--> <mappers> <package name="com.itwen.mapper"/> </mappers> </configuration>
webapp
WEB-INF
web.xml(这个不自己写,创建项目结构时使用idea生成)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> </web-app>
brand.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 引入vue2 --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/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> <!-- 引入axios发ajax --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <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="primary" @click="deleteByIds" plain>批量删除</el-button> <el-button type="danger" @click="dialogVisible = true" plain>新增</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> </span> </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" label="排序" align="center"> </el-table-column> <el-table-column prop="statusStr" label="当前状态" align="center"> </el-table-column> <el-table-column label="操作" align="center"> <template slot-scope="scope"> <el-button type="primary" @click="showUpdateBrand(scope.row)">修改</el-button> <el-button type="danger" @click="deleteBrand(scope.row)">删除</el-button> </template> </el-table-column> </el-table> </template> <!--修改数据对话框标表单--> <el-dialog title="编辑品牌" :visible.sync="dialogFormVisible" width="30%"> <el-form ref="form" :model="brand2" label-width="80px"> <el-form-item label="品牌名称"> <el-input v-model="brand2.brandName"></el-input> </el-form-item> <el-form-item label="企业名称"> <el-input v-model="brand2.companyName"></el-input> </el-form-item> <el-form-item label="排序"> <el-input v-model="brand2.ordered"></el-input> </el-form-item> <el-form-item label="备注"> <el-input type="textarea" v-model="brand2.description"></el-input> </el-form-item> <el-form-item label="状态"> <el-switch v-model="brand2.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="dialogFormVisible = false">取消</el-button> </el-form-item> </el-form> </el-dialog> <!--分页工具条--> <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> <style> </style> <script> new Vue({ el: "#app", mounted() { //当页面加载完成后,发送异步请求获取数据 this.selectAll(); }, data() { return { //表格数据 tableData: [{ brandName: "华为(测试数据1)", companyName: "华为公司-页面能看到表明未获取到数据库数据", ordered: "100", status: "1", }, { brandName: "华为(测试数据2)", companyName: "华为公司", ordered: "100", status: "1", }], //复选框选中数据集合 multipleSelection: [], //搜索表单数据 brand: { status: "", companyName: "", brandName: "", id: "", ordered: "", description: "", }, //修改表单数据 brand2: { status: "", companyName: "", brandName: "", id: "", ordered: "", description: "", }, //添加数据对话框是否展示的标记 dialogVisible: false, //当前页码 currentPage: 1, //被选中的品牌的id数组 selectedIds: [], //总记录数 totalCount: 100, //每页条数 pageSize: 5, //是否显示修改数据表单 dialogFormVisible: false, } }, methods: { //查询当前页数据 selectAll() { /* var _this=this; axios({ method: "get", url: "http://localhost:8080/brand-case/brand/selectAll" }).then(function(response){ _this.tableData = response.data; })*/ axios({ method: "post", url: "http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize, data: this.brand, }).then(response => { //设置表格数据 this.tableData = response.data.rows;//{"rows":[],"totalCount":52} //设置总记录数 this.totalCount = response.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); //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/brand-case/brand/add", data: this.brand }).then(response => { if (response.data == "success") { //添加成功 //关闭窗口 this.dialogVisible = false; //重新查询数据 this.selectAll(); //弹出成功提示 this.$message({ message: "添加成功", type: "success" }); } ; }) }, //显示要修改的数据 showUpdateBrand(row) { // console.log(row);//当前行数据 this.brand2 = JSON.parse(JSON.stringify(row));//传值不传址,防止数据一起变 this.brand2.status += "";//之前获取的status是数字,需要转成字符串才能被识别 this.dialogFormVisible = true;//显示窗体 }, //修改数据 updateBrand() { //弹出确认提示框 this.$confirm("此操作将永久修改该信息, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(() => { //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/brand-case/brand/update", data: this.brand2 }).then(response => { if (response.data == "success") { //添加成功 //关闭窗口 this.dialogFormVisible = false; //重新查询数据 this.selectAll(); //弹出成功提示 this.$message({ message: "修改成功", type: "success" }); } ; }) }).catch(() => { //用户点击取消按钮 this.$message({ type: "info", message: "已取消修改" }); }); }, //删除数据 deleteBrand(row) { //console.log(row.id);//当前行品牌数据的id this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(() => { //发送ajax请求,添加数据 axios({ method: "post", url: "http://localhost:8080/brand-case/brand/deleteById", data: row.id }).then(response => { if (response.data == "success") { //删除成功 //重新查询数据 this.selectAll(); //弹出成功提示 this.$message({ message: "删除成功", type: "success" }); } ; }) }).catch(() => { //用户点击取消按钮 this.$message({ type: "info", message: "已取消删除" }); }); }, //分页 handleSizeChange(val) { // console.log(`每页 ${val} 条`); //重新设置每页条数 this.pageSize = val; this.selectAll(); }, handleCurrentChange(val) { // console.log(`当前页: ${val}`); //重新设置当前页码 this.currentPage = val; this.selectAll(); }, //批量删除 deleteByIds() { //弹出确认提示框 this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(() => { //用户点击确认按钮 //1,创建id数组[1,2,3] // console.log(this.multipleSelection); for (let i = 0; i < this.multipleSelection.length; i++) { let selectionElement = this.multipleSelection[i]; this.selectedIds[i] = selectionElement.id; } //发送ajax请求 axios({ method: "post", url: "http://localhost:8080/brand-case/brand/deleteByIds", data: this.selectedIds }).then(response => { if (response.data == "success") { //删除成功 //重新查询数据 this.selectAll(); //弹出成功提示 this.$message({ message: "删除成功", type: "success" }); } ; }); }).catch(() => { //用户点击取消按钮 this.$message({ type: "info", message: "已取消删除" }); }); }, }, }) </script> </body> </html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>brand-case</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope><!--编译和测试环境有效,运行环境无效。因为tomcat自带了这个jar包,会冲突--> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </build> </project>