【黑马程序员】Javaweb综合案例

框架

环境搭建

(1)pom.xml

(注意,mysql版本请与自己的相匹配)

<?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>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--Servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--MyBatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--fastjson-->
        <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>

(2)实体类下的Brand类

package com.itheima.pojo;

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
    
    public 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 +
                '}';
    }
}

(3) BrandMapper.java 与 BrandMapper.xml

(4)SqlSessionFactoryUtils.java(mybatis-config.xml处是你自己的文件路径)

 

 (5)由于我们在用一种很新的方法写servlet

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;

/*替换HttpServlet,根据请求路径的最后一段,进行方法分发(get or post)*/
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 */
        //2.获取最后一段路径,方法名
        int index = uri.lastIndexOf('/');/*从后开始获取某个字符第一次出现的位置索引*/
        String methodName = uri.substring(index+1);//从该索引位置进行剪切,至字符串的最有一位(包含'/')
        //执行方法
        //1.获取brandservlet的字节码对象class
        Class<? extends BaseServlet> cls = this.getClass();
        //2.获取method对象
        try {
            Method cm = cls.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //3.执行方法
            try {
                cm.invoke(this,req,resp);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}

(6)BrandServletImpl.java 定义接口

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

(7)PageBean实体类

package com.itheima.pojo;

import java.util.List;
//分页查询
public class PageBean<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;
    }
}

  (8)查询所有

public interface BrandMapper {
//    查询所有
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();
}
public class BrandServiceImpl implements BrandService {
    //1.创建 SqlSessionFactory 工厂
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    //查询操作
    @Override
    public List<Brand> selectAll() {
        //2.获取SqllSession对象
        SqlSession session = factory.openSession();
        //3.获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        //5.释放资源
        session.close();
        return brands;
    }
}
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
    private BrandService brandService = new BrandServiceImpl();
    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.调用service查询
        List<Brand> brands = brandService.selectAll();
        //2.转为JSON
        String s = JSON.toJSONString(brands);
        //3.写数据
        //中文
        resp.setContentType("text/json;charset=UTF-8");
        resp.getWriter().write(s);
    }
}

 

//分页条件查询
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();//json字符串
        //转为 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);
    }
//查询分页数据
selectAll(){
    //查询所有数据
    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:[]}
     this.tableCount = resp.data.totalCount;
     })
},

(9)data(){}

data() {
            return {
                //默认每页5条数据
                pageSize:5,
                //总记录数
                tableCount:100,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,
                dialogVisible2: false,
                tableData:{},
                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },
                // 复选框选中数据集合
                multipleSelection: [],
                selectByIds:[]
            }

(10)添加数据

//添加
    @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);
//添加操作
    @Override
    public void add(Brand brand) {
        //2.获取SqlSession对象
        SqlSession session = factory.openSession();
        //3.获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //4.调用方法
        mapper.add(brand);
        session.commit();
        session.close();
    }
public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受品牌数据(JSON格式)
        BufferedReader br = req.getReader();
        String params = br.readLine();//读取一行,JSON全部数据就是一行

        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        //调用service添加
        brandService.add(brand);
        //响应数据成功的标识
        resp.getWriter().write("success");
    }

 

// 添加数据
            addBrand(){
                // console.log(this.brand);
                //添加axios请求,添加数据
                var _this = this;
                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'
                        });
                    }
                })
            },

(11)修改方法

//修改
    @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")
    void update(Brand brand);
//修改操作
    @Override
    public void update(Brand brand){
        //获取SQLSession对象
        SqlSession session = factory.openSession();
        //获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //调用方法
        mapper.update(brand);
        session.commit();
        session.close();
    }
//    修改
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受品牌数据(JSON格式)
        BufferedReader br = req.getReader();
        String params = br.readLine();//读取一行,JSON全部数据就是一行
        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        //调用service修改
        brandService.update(brand);
        resp.getWriter().write("success");
    }

 

 

updateBrand(){
                //修改数据
                //添加axios请求,添加数据
                var _this = this;
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/update",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //修改成功
                        //关闭窗口
                        _this.dialogVisible2 = false;
                        //查询所有
                        _this.selectAll();
                        _this.$message({
                            message:'修改成功了少年郎',
                            type:'success'
                        });
                    }
                })
            },

(12) 删除方法

//删除
    @Delete("delete from tb_brand where id = #{id}")
    void deleteById(int id);
//删除操作
    @Override
    public void deleteById(int id){
        //获取SQLSession对象
        SqlSession session = factory.openSession();
        //获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //调用方法
        mapper.deleteById(id);
        session.commit();
        session.close();
    }
//删除
    public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受品牌数据(JSON格式)
        BufferedReader br = req.getReader();
        String params = br.readLine();//读取一行,JSON全部数据就是一行
        //转为 int
        int id = JSON.parseObject(params,int.class);
        //调用service修改
        brandService.deleteById(id);
        resp.getWriter().write("success");
    }
//删除数据
            deleteById(index,row) {
                // 弹出确认提示框
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //2. 发送AJAX请求
                    var _this = this;
                    // 发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteById",
                        data:row.id
                    }).then(function (resp) {
                        if(resp.data == "success"){
                            //删除成功
                            // 重新查询数据
                            _this.selectAll();
                            // 弹出消息提示
                            _this.$message({
                                message: '删除成功了少年郎',
                                type: 'success'
                            });
                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

(13) 批量删除方法

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

 BrandMapper.xml下添加

<delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
//批量删除操作
    @Override
    public void deleteByIds(int[] ids){
        //获取SQLSession对象
        SqlSession session = factory.openSession();
        //获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //调用方法
        mapper.deleteByIds(ids);
        session.commit();
        session.close();
    }
//批量删除
    public void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受品牌数据(JSON格式)
        BufferedReader br = req.getReader();
        String params = br.readLine();//读取一行,JSON全部数据就是一行
        //转为Brand对象
        int[] ids = JSON.parseObject(params, int[].class);
        //调用service修改
        brandService.deleteByIds(ids);
        resp.getWriter().write("success");
    }
deleteByIds() {
                //console.log(this.multipleSelection);
                //1.创建id数组[1,2,3],从multipleSelection模型里面来的数据

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let element = this.multipleSelection[i];
                        //获取遍历后得到id值
                        this.selectByIds[i] = element.id;

                    }
                    var _this = this;
                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteByIds",
                        data: _this.selectByIds
                    }).then(resp => {
                        if (resp.data == "success") {
                            //录入成功,关闭窗口,并且重新查询数据
                            _this.selectAll();
                            _this.$message({
                                message: '成功删除数据',
                                type: 'success'
                            });
                        }else{
                            _this.$message({
                                message: '没有数据可以删除',
                                type: 'info'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },

 

 (14)分页查询(和普通查询方法一样会被 “条件分页查询替代” )

//分页查询-查询当前页
    @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();

 

@Override
    public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
        //获取SQLSession对象
        SqlSession session = factory.openSession();
        //获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //计算开始索引
        int begin = (currentPage-1)*pageSize;
        //计算总体数据数量
        int size = pageSize;
        //查询总数
        int totalCount = mapper.selectTotalCount();
        //调用方法
        List<Brand> rows = mapper.selectByPage(begin, size);
        //封装函数
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(rows);

        session.close();
        return pageBean;
    }
//分页查询
    public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*接收参数
        * currentPage:当前页码
        * PageSize:每页条数
        * http://localhost:8080/brand-case/brand/selectByPage?currentPage=1&pageSize=5
        * */
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        //2. 调用service查询
        PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
        //2.转为JSON
        String s = JSON.toJSONString(pageBean);
        //3.写数据
        //中文
        resp.setContentType("text/json;charset=UTF-8");
        resp.getWriter().write(s);
    }

(15)条件分页查询
 

//条件查询-分页查询
    List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);
    //总记录数-满足查询条件的
    int selectTotalCountByCondition(Brand brand);

<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>
@Override
    public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
        //获取SQLSession对象
        SqlSession session = factory.openSession();
        //获取brandmapper
        BrandMapper mapper = session.getMapper(BrandMapper.class);
        //计算开始索引
        int begin = (currentPage-1)*pageSize;
        //计算总体数据数量
        int size = pageSize;

        //处理模糊算法
        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<Brand> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(rows);

        session.close();
        return pageBean;
    }

 

//分页条件查询
    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();//json字符串
        //转为 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);
    }
//分页
            //每页条数发生变化
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                //重新设置每页条数
                this.pageSize = val;
                this.selectAll();
            },
            //页数发生变化
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                //重新设置当前页码
                this.currentPage = val;
                this.selectAll();
            }
        },

(15)总的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>

    <!--表格-->
    <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="操作">
            <template slot-scope="scope">
                <el-row>
                    <el-button type="primary" plain @click="updateById(scope.$index, scope.row)">修改</el-button>
                    <el-button type="danger"  plain @click="deleteById(scope.$index, scope.row)">删除</el-button>
                </el-row>

                <!--修改数据对话框表单-->
                <el-dialog
                        title="编辑品牌"
                        :visible.sync="dialogVisible2"
                        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 >
                            <template slot-scope="scope">
                                <el-button type="primary" @click="updateBrand">提交</el-button>
                                <el-button @click="dialogVisible2 = false">取消</el-button>
                            </template>
                        </el-form-item>
                    </el-form>
                </el-dialog>
            </template>
        </el-table-column>
    </el-table>

    <!--分页工具条-->
    <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="tableCount">
    </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();
        },
        methods: {
            //查询分页数据
            selectAll(){
                //查询所有数据
                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:[]}
                    this.tableCount = 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() {
                this.selectAll();
            },
            // 添加数据
            addBrand(){
                // console.log(this.brand);
                //添加axios请求,添加数据
                var _this = this;
                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'
                        });
                    }
                })
            },
            updateById(index,row) {
                this.brand.id = row.id;
                this.dialogVisible2 = true;
            },
            updateBrand(){
                //修改数据
                //添加axios请求,添加数据
                var _this = this;
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-case/brand/update",
                    data:_this.brand
                }).then(function (resp){
                    if(resp.data == "success"){
                        //修改成功
                        //关闭窗口
                        _this.dialogVisible2 = false;
                        //查询所有
                        _this.selectAll();
                        _this.$message({
                            message:'修改成功了少年郎',
                            type:'success'
                        });
                    }
                })
            },
            //删除数据
            deleteById(index,row) {
                // 弹出确认提示框
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    //2. 发送AJAX请求
                    var _this = this;
                    // 发送ajax请求,添加数据
                    axios({
                        method:"post",
                        url:"http://localhost:8080/brand-case/brand/deleteById",
                        data:row.id
                    }).then(function (resp) {
                        if(resp.data == "success"){
                            //删除成功
                            // 重新查询数据
                            _this.selectAll();
                            // 弹出消息提示
                            _this.$message({
                                message: '删除成功了少年郎',
                                type: 'success'
                            });
                        }
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteByIds() {
                //console.log(this.multipleSelection);
                //1.创建id数组[1,2,3],从multipleSelection模型里面来的数据

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let element = this.multipleSelection[i];
                        //获取遍历后得到id值
                        this.selectByIds[i] = element.id;

                    }
                    var _this = this;
                    axios({
                        method: "post",
                        url: "http://localhost:8080/brand-case/brand/deleteByIds",
                        data: _this.selectByIds
                    }).then(resp => {
                        if (resp.data == "success") {
                            //录入成功,关闭窗口,并且重新查询数据
                            _this.selectAll();
                            _this.$message({
                                message: '成功删除数据',
                                type: 'success'
                            });
                        }else{
                            _this.$message({
                                message: '没有数据可以删除',
                                type: 'info'
                            });
                        }
                    })
                }).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();
            }
        },
        data() {
            return {
                //默认每页5条数据
                pageSize:5,
                //总记录数
                tableCount:100,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisible: false,
                dialogVisible2: false,
                tableData:{},
                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id:"",
                    ordered:"",
                    description:""
                },
                // 复选框选中数据集合
                multipleSelection: [],
                selectByIds:[]
            }
        }
    })

</script>

</body>
</html>

  • 0
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值