SpringBoot + Vue (ElementUI)的小例子

关于SpringBoot项目的搭建,Vue的环境搭建这里不再中赘述。

1.首先建立数据库表:

DROP TABLE IF EXISTS `semester`;
CREATE TABLE `semester`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `semesterid` char(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '学习编号',
  `semestername` varchar(400) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '学期名称',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 38 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2.后端Mapper层:

package com.justcs.mapper;

import com.justcs.entity.Semester;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface SemesterMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Semester record);

    int insertSelective(Semester record);

    Semester selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Semester record);

    int updateByPrimaryKey(Semester record);


    /**
     * 查询所有的学期信息
     * @param semsname
     * @param sortby
     * @param order
     * @return
     */
    @Select({
            "<script>",
            "select * from semester",
            "where 1 = 1",
            // 判断条件
            "<if test='semsname !=null and semsname!=&apos;&apos;'>",
                "and semestername like CONCAT(CONCAT('%', #{semsname}), '%')",
            "</if>",
            // 按照某个字段排序
            "<if test='sortby!=null and sortby!=&apos;&apos; and order !=null and order!=&apos;&apos;'>",
                "order by ${sortby} ${order}",
            "</if>",
            "</script>"
    })
    List<Semester> selectSemester(@Param("semsname") String semsname, @Param("sortby") String sortby, @Param("order") String order);


    /**
     * 批量删除学期信息
     * @param semesters
     * @return
     */
    @Delete({
            "<script>",
            "delete from semester",
            "where id in",
            "<foreach collection='ids' item='arr' open='(' separator=',' close=')'>",
            "#{arr}",
            "</foreach>",
            "</script>"
    })
    int batchDeleteSemester(@Param("ids") int[] semesters);
}

3.Service层:

package com.justcs.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.justcs.entity.Semester;
import com.justcs.form.PagedQueryForm;
import com.justcs.form.Semesters_c;
import com.justcs.mapper.SemesterMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysConfService {

    @Autowired
    private SemesterMapper semesterMapper;

    /**
     * 分页查询所有的学期信息
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public PageInfo<Semester> queryPagedSemester(PagedQueryForm<Semesters_c> query) {
        if(query!=null) {
            PageHelper.startPage(query.getPage(), query.getPagesize());
            PageInfo<Semester> semesterPageInfo = new PageInfo<>(
                    semesterMapper.selectSemester(query.getSearch().getSemestername(), query.getSort(), query.getOrder())
            );
            return semesterPageInfo;
        }
        return null;
    }

    /**
     * 添加学期
     * @param semester
     * @return
     */
    @Transactional
    public int addSemester(Semester semester) {
        if (semester != null) {
            return semesterMapper.insertSelective(semester);
        }
        return 0;
    }

    /**
     * 根据主键修改学期
     * @param semester
     * @return
     */
    @Transactional
    public int modifySemester(Semester semester) {
        if (semester!=null && semester.getId() != null) {
            return semesterMapper.updateByPrimaryKeySelective(semester);
        }
        return 0;
    }

    /**
     * 根据主键删除学期
     * @param semester
     * @return
     */
    @Transactional
    public int removeSemester(Semester semester) {
        if (semester!=null && semester.getId() != null) {
            return semesterMapper.deleteByPrimaryKey(semester.getId());
        }
        return 0;
    }

    /**
     * 批量删除学期信息
     * @param semesters
     * @return
     */
    @Transactional
    public int batchRemoveSemester(int[] semesters) {
        if(semesters!=null && semesters.length>0) {
            return semesterMapper.batchDeleteSemester(semesters);
        }
        return 0;
    }


}

4.Controller层:

package com.justcs.controller;


import com.github.pagehelper.PageInfo;
import com.justcs.entity.Semester;
import com.justcs.form.PagedQueryForm;
import com.justcs.form.Semesters_c;
import com.justcs.service.SysConfService;
import com.justcs.utils.JSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@Api(value = "系统配置控制层")
@RestController
@RequestMapping("/sys")
public class SysConfController {

    private static final Logger logger = LoggerFactory.getLogger(SysConfController.class);

    @Autowired
    private SysConfService sysConfService;

    /**
     * 分页查询所有学期信息
     *
     * @return
     */
    @PostMapping("/querySemesters")
    @ApiOperation(value = "分页按照条件查询所有的学期的信息")
    public JSONResult querySemesters(@RequestBody @Valid PagedQueryForm<Semesters_c> param) {
        try {
            PageInfo<Semester> result = sysConfService.queryPagedSemester(param);
            return JSONResult.ok(result);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw  e;
        }
    }

    /**
     * 新增学期
     * @param semester
     * @return
     */
    @PostMapping("/addSemester")
    @ApiOperation(value = "新增学期")
    public JSONResult addSemester(@RequestBody(required = true) Semester semester) {
        try {
            int affected = sysConfService.addSemester(semester);
            return affected > 0 ? JSONResult.ok() : JSONResult.errorMsg("录入失败!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 删除学期信息
     * @param semesterid
     * @return
     */
    @PostMapping("/rmSemester/{semesterid}")
    @ApiOperation(value = "删除学期信息")
    public JSONResult removeSemester(@PathVariable("semesterid") int semesterid){
        Semester semester = new Semester();
        semester.setId(semesterid);
        try {
            int affected = sysConfService.removeSemester(semester);
            return affected > 0? JSONResult.ok() : JSONResult.errorMsg("删除失败!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 批量删除学期信息
     * @param arrs
     * @return
     */
    @PostMapping("/bhrmsemester")
    @ApiOperation(value = "批量删除学期信息")
    public JSONResult batchRemoveSemester(@RequestBody(required = true) int[] arrs) {
        try {
            int affected = sysConfService.batchRemoveSemester(arrs);
            return affected > 0? JSONResult.ok() : JSONResult.errorMsg("批量删除失败!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 修改学期信息
     * @param semester
     * @return
     */
    @PostMapping("/mdsemester")
    @ApiOperation(value = "修改学期信息")
    public JSONResult mdsemester(@RequestBody(required = true) Semester semester) {
        try {
            int affected = sysConfService.modifySemester(semester);
            return affected > 0? JSONResult.ok() : JSONResult.errorMsg("修改失败!");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

}

5.前端index.vue文件:

<template>
  <div style="width:80%;margin: 0 auto;">
    <div style="margin-top:20px;">
      <el-row :gutter="5">
        <el-col :span="6">
          <el-button type="warning" @click="batchremote">删除</el-button>
          <el-button type="success" @click="addsemester">新增</el-button>
        </el-col>
        <el-col :span="18">
          <el-form :inline="true" style="float:right;">
            <el-form-item>
              <el-input v-model="conditions.search.semestername" placeholder="请输入关键字" @keyup.enter.native="conditionsearch"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="conditionsearch">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      :data="tableData"
      height="600"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="handlerSortchange">
      <!-- 多选 -->
      <el-table-column
        type="selection"
        width="40"
        style="text-align:center;"/>
      <el-table-column
        prop="id"
        label="编号"
        sortable = "custom"
        width="180"/>
      <el-table-column
        prop="semesterid"
        label="学期代码"
        sortable = "custom"
        width="180"/>
      <el-table-column
        prop="semestername"
        sortable = "custom"
        label="学期名称"/>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <el-pagination
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      background
      layout="prev, pager, next"
      @current-change="handlecurrentchange"/>

    <!-- 修改模态框 -->
    <el-dialog :visible.sync="dialogFormVisible" width="50%" title="修改学期">
      <el-form :model="semesterform">
        <el-form-item label-width="120px" label="学期编号">
          <el-input v-model="semesterform.semesterid" clearable placeholder="请输入学期编号"/>
        </el-form-item>
        <el-form-item label-width="120px" label="学期名称">
          <el-input v-model="semesterform.semestername" clearable placeholder="请输入学期名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="suremodify">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增模态框 -->
    <el-dialog :visible.sync="newFormVisible" width="50%" title="新增学期">
      <el-form :model="semesterform">
        <el-form-item label-width="120px" label="学期编号">
          <el-input v-model="semesterform.semesterid" clearable placeholder="请输入学期编号"/>
        </el-form-item>
        <el-form-item label-width="120px" label="学期名称">
          <el-input v-model="semesterform.semestername" clearable placeholder="请输入学期名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddSemester">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { getList, modifySemester, removeSemester, batchrmSemester, newSemester } from '../../api/table'
export default {
  data() {
    return {
      currentPage: 1, // 当前页面
      total: 1000, // 总记录数
      pageSize: 10, // 每页的大小
      multipleSelection: [], // 多选数组
      // 表格具体内容
      tableData: [],
      // 查询条件
      conditions: {
        order: '',
        sort: '',
        page: 1,
        pagesize: 10,
        search: {
          semestername: ''
        }
      },
      // 修改表单是否隐藏
      dialogFormVisible: false,
      // 修改表单
      semesterform: {
        id: '', // 编号
        semesterid: '', // 学期编号
        semestername: '' // 学期名称
      },

      // 新增表单是否隐藏
      newFormVisible: false
    }
  },
  created() {
    // 抓取数据
    this.fetchData()
  },
  methods: {
    // 选择发生变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击跳转页面变化
    handlecurrentchange(val) {
      this.currentPage = val
      this.conditions.page = val
      this.fetchData()
    },
    // 分页抓取数据
    fetchData() {
      getList(this.conditions).then(response => {
        const data = response.data
        this.tableData = data.list
        this.total = data.total
        this.currentPage = data.pageNum
      })
    },
    // 编辑
    handleEdit(index, row) {
      this.semesterform.id = row.id
      this.semesterform.semesterid = row.semesterid
      this.semesterform.semestername = row.semestername
      this.dialogFormVisible = true
    },
    // 删除
    handleDelete(index, row) {
      const semesterid = row.id
      this.$confirm('你确定要删除' + row.semestername + '吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeSemester(semesterid).then(response => {
          console.log(response)
          this.$message.success('删除成功!')
          // 重新fetchdata
          this.fetchData()
        })
      }).catch(() => {
        this.$message.info('已取消删除!')
      })
    },
    // 批量删除
    batchremote() {
      const delids = this.multipleSelection.map((e, i, arr) => {
        return e.id
      })
      if (delids.length > 0) {
        this.$confirm('你确定要删除这' + delids.length + '条记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchrmSemester(delids).then(response => {
            if (response.ok) {
              this.$message.success('删除成功')
              // 重新fetchdata
              this.fetchData()
            } else {
              this.$message.error(response.msg)
            }
          })
        }).catch(() => {
          this.$message.info('已取消删除!')
        })
      } else {
        this.$message.warning('请先选择记录!')
      }
    },
    // 处理排序
    handlerSortchange(sortobj) {
      this.conditions.sort = sortobj.prop // 待排序的字段
      this.conditions.order = (sortobj.order === 'descending') ? 'desc' : (sortobj.order === 'ascending' ? 'asc' : '')
      this.fetchData()
    },
    // 确定修改
    suremodify() {
      modifySemester(this.semesterform).then(response => {
        console.log(response)
        if (response.ok) {
          this.$message.success('修改成功')
          this.dialogFormVisible = false
          // 重新featchdada
          this.fetchData()
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    // 按照条件查询
    conditionsearch() {
      this.fetchData()
    },
    // 新增
    addsemester() {
      this.newFormVisible = true
      this.semesterform = {}
    },
    // 确定新增
    sureAddSemester() {
      this.semesterform.id = ''
      newSemester(this.semesterform).then(response => {
        if (response.ok) {
          this.$message.success('添加成功!')
          this.newFormVisible = false
          this.fetchData()
        } else {
          this.$message.error(response.msg)
        }
      })
    }
  }
}
</script>

6.展示结果:

后记:本身内容并不复杂,DEMO采取的目前主流的技术SpringBoot+Vue + ElementUI ,前后端分离的解决方案。仅此记录,方便后续开发人员参考,节省时间。

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值