黑马程序员Java Web--14.综合案例--修改功能实现

一、BrandMapper包

首先,在BrandMapper包中定义用来修改的方法,和使用注解的sql语句。

BrandMapper包所在路径:
package com.itheima.mapper;

   /**
    *
    * 修改
    * 
    **/
    @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")
    void upDate(Brand brand);

二、BrandService

BrandService中定义一个提供修改的方法接口,用来给BrandServiceImpl进行具体方法的实现。

BrandService包所在路径:
package com.itheima.service;

 void upDate(Brand brand);

三、BrandServiceImpl

在BrandServiceImpl重写BrandService接口中提供的upDate方法。

BrandServiceImpl包所在路径:
package com.itheima.service.impl;

@Override
    public void upDate(Brand brand){
        //2.获取sqlsession对象
        SqlSession sqlSession = factory.openSession();
        //3.获取Mapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用upDate方法
         mapper.upDate(brand);
        //sql事务提交
        sqlSession.commit();
        //关闭sql
        sqlSession.close();
        
    }

四、BrandServlet

在BrandServlet中实现upDate Servlet的功能。

BrandServlet路径:
package com.itheima.web.servlet;

 public void upDate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 接收品牌数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串
       System.out.println("par:"+params);
        //转为Brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        System.out.println("brand:"+brand);

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

        //3. 设置编码方式
        response.setContentType("text/json;charset=utf-8");
        //4. 响应成功的标识
        response.getWriter().write("success");
    }

五、前端代码

首先,添加一个修改数据的表单。这段代码位置可以放在网页数据表单的上方。

 

    <el-dialog
            title="修改品牌"
            :visible.sync="updateDialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-input v-model="brand.id" type="hidden">el-input>
            <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="edit">提交el-button>
                <el-button @click="updateDialogVisible = false">取消el-button>
            el-form-item>
        el-form>

    el-dialog>

这段代码中定义了一个判定是否显示表单的变量:updateDialogVisible
我们需要在script中的data中进行定义:

data(){
   return{
 updateDialogVisible: false,
   }
 }  

在你自己项目中只复制updateDialogVisible: false, 就可以了。

在methods里面添加如下方法

 //修改
            updateBrand(index,row){
                this.brand.id=row.id;
                this.updateDialogVisible=true;
                this.brand = JSON.parse(JSON.stringify(row));
            },
            edit(){
                var _this=this;
                axios({
                    method:"post",
                    url:"http://localhost:8098/brand-case/brand/upDate",
                    data:_this.brand
                }).then(response =>{
                        if (response.data == "success") {
                                    //添加成功
                                    _this.updateDialogVisible = false
                                    //刷新
                                    _this.selectAll();

                                    _this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });

                                }
                })

            },

其中updateBrand函数是我们点击修改按钮时绑定的click方法

在网页显示数据的表单代码段中,找到修改button所在位置,给@click添加点击事件的函数updateBrand。
以及这里需要获取表单中某行的id值用来获得需要修改行现有的值,所以使用:slot-scope
(ps:这段代码直接复制替换原来修改删除的位置就好)

 <template slot-scope="scope">
                <el-row>
                    <el-button type="primary" @click="updateBrand(scope.$index,scope.row)">修改</el-button>
                    <el-button type="danger">删除</el-button>
                </el-row>
                </template>

六、brand.html 全部代码展示:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <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-dialog
            title="修改品牌"
            :visible.sync="updateDialogVisible"
            width="30%"
    >

        <el-form ref="form" :model="brand" label-width="80px">
            <el-input v-model="brand.id" type="hidden">el-input>
            <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="edit">提交el-button>
                <el-button @click="updateDialogVisible = false">取消el-button>
            el-form-item>
        el-form>

    el-dialog>


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

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

            <el-table-column
                    align="center"
                    label="操作"
                      >
                <template slot-scope="scope">
                <el-row>
                    <el-button type="primary" @click="updateBrand(scope.$index,scope.row)">修改el-button>
                    <el-button type="danger">删除el-button>
                el-row>
                template>
            el-table-column>

        el-table>
    template>

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

div>


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

<script>
    new Vue({
        el: "#app",
        mounted() {
            this.selectAll()

        },
        methods: {

            selectAll() {
                //页面加载完成后,获取数据
                var _this = this;
                axios({
                    method: "get",
                    url: "http://localhost:8098/brand-case/brand/selectAll",
                }).then(response => {
                    this.tableData = response.data;
                    console.log(_this.tableData)
                })
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            //修改
            updateBrand(index,row){
                this.brand.id=row.id;
                this.updateDialogVisible=true;
                this.brand = JSON.parse(JSON.stringify(row));
            },
            edit(){
                var _this=this;
                axios({
                    method:"post",
                    url:"http://localhost:8098/brand-case/brand/upDate",
                    data:_this.brand
                }).then(response =>{
                        if (response.data == "success") {
                                    //添加成功
                                    _this.updateDialogVisible = false
                                    //刷新
                                    _this.selectAll();

                                    _this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });

                                }
                })

            },

              // axios({
              //     method:"post",
              //     url:"http://localhost:8098/brand-case/brand/upDate",
              // }).then(response => {
              //     if (response.data == "success") {
              //         //添加成功
              //         _this.updateDialogVisible = false
              //         //刷新
              //         _this.selectAll();
              //
              //         _this.$message({
              //             message: '修改成功',
              //             type: 'success'
              //         });
              //
              //     }
              // })

            //点击修改后唤起修改框
            startUpdate(row) {
                // 获取改行已经有的数据,以供填入修改框
                // var _this = this
                this.brand = JSON.parse(JSON.stringify(row));
                // 弹出修改框
                this.updateDialogVisible = true;
            },

            // 复选框选中后执行的方法
            handleSelectionChange(val) {
                this.multipleSelection = val;

                console.log(this.multipleSelection)
            },
            // 查询方法
            onSubmit() {
                console.log(this.brand);
            },
            // 添加数据
            addBrand() {
                var _this = this;
                axios({
                    method: "post",
                    url: "http://localhost:8098/brand-case/brand/add",
                    data: _this.brand
                }).then(function (resp) {
                    if (resp.data == "success") {
                        //添加成功
                        _this.dialogVisible = false
                        //刷新
                        _this.selectAll();

                        _this.$message({
                            message: '添加成功',
                            type: 'success'
                        });

                    }
                })

            },
            //批量删除
            deleteByIds() {
                // 弹出确认提示框

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

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

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

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

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

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

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


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

        },

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

                // 品牌模型数据
                brand: {
                    status: '',
                    brandName: '',
                    companyName: '',
                    id: "",
                    ordered: "",
                    description: ""
                },
                // 被选中的id数组
                selectedIds:[],
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据
                tableData: [{}]
            }
        },

    })

script>

body>
html>

七、解决修改、添加中文字符显示问号

在mybatis-config.xml中,在数据库配置路径后添加:
characterEncoding=utf-8

jdbc:mysql:///db1?useSSL=false&characterEncoding=utf-8

参考文章:
https://blog.csdn.net/qq_42078934/article/details/125436314
https://blog.csdn.net/qq_51272114/article/details/127039314

能力有限,欢迎指正!

你可能感兴趣的:(JavaWeb黑马学习,java,前端,开发语言)