欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

程序员文章站 2022-05-06 18:05:02
...

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

1-Vue基本用法

1.1 V-model进行双向事件的绑定

<!--1-v-model用来渲染 进行事件的交互-->
                    <input type="text" v-model="message">
                    {{message}}

1.2 V-on:事件名称 进行事件的绑定 简化成@click=“方法名称()”

<!--2事件处理:vue的事件绑定采用v-on:事件名称 简化成@事件进行绑定--->
                    <input type="button" value="+" @click="add()" >
                    {{num}}
                    <input type="button" value="-" @click="sub()">

1.3 钩子函数 生命周期 :常用的方法:created:当Vue实例创建后 再加载方法

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

1.4 V-bind:class 绑定样式 如果键与值相同 则可以直接写键 不用写值

<div :class="{active,hasError}" v-model="message">
                            {{message}}
                    </div>

1.5 计算属性 computed:计算属性

<!--5-计算属性本质就是方法 但是一定要返回数据 然后页面进行渲染时,
                    可以把这个方法当成一个变量来使用-->
                    <h2>
                        您的生日为:{{birth}}
                    </h2>

1.6 监听变量 watch

 watch:{
            message(newVal,oldVal){  //参数1:新值 参数2:旧值
                console.log("新值"+newVal+"旧值"+oldVal);
            }

        }

1.7 创建Vue实例: el:在哪个区间范围内 data:变量数据 methods:执行的方法

<script>
    new Vue({
        el:".d",
        data:{
            message:"张三",
            num: 1,
            hello:"" ,//初始化内容为空
            active:true,
            hasError:false,
            birthday:1529032123201,
        },
        methods:{
            add(){  //添加数
                this.num +=1;
            },
            sub(){  //减少数
                if(this.num <=1){
                    this.num = 1;
                }else{
                    this.num -=1;
                }


            }
        },
        computed:{   //计算属性
            birth(){
                let dt = new Date(this.birthday);
                return dt.getFullYear()+"年"+(dt.getMonth()+1)+"月"+dt.getDate()+"日";
            }
        },
        //监听变量
        watch:{
            message(newVal,oldVal){  //参数1:新值 参数2:旧值
                console.log("新值"+newVal+"旧值"+oldVal);
            }

        }
    })
</script>

2-Vue+Element UI +cp30连接池实现学生管理系统

2.1 cp30配置文件

创建resources文件夹 并Mark as resources root 标记为资源文件夹

c3p0-config.xml: 这个文件名绝对不能变

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置 -->
    <default-config>
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/chrisfeng</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
    </default-config>
</c3p0-config>

2.2 下载对应的jar包

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

2.3 下载Vue需要的js文件以及实现异步加载的axios.js文件(axios需要依赖于vue.js)以及下载element ui需要的css样式以及js文件

  • 先安装node.js
  • 然后使用命令下载
npm i element-ui -S --save 下载element ui

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

2.4 把web下的index.jsp文件删掉 新建index.html文件

Element UI 官方网址: https://element.eleme.cn

**Vue官网:**https://cn.vuejs.org/v2/guide/

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生列表</title>
    <!--1.引入vue-->
    <script src="plugins/vue.min.js"></script>
    <!--2.引入axios-->
    <script src="plugins/axios.min.js"></script>
    <!-- 3.引入样式 -->
    <link rel="stylesheet" href="plugins/element-ui/lib/theme-chalk/index.css">
    <!-- 4.引入组件库 -->
    <script src="plugins/element-ui/lib/index.js"></script>
    <style>
        .el-row {
            margin-bottom: 20px;
        &:last-child {
             margin-bottom: 0;
         }
        }
        .el-col {
            border-radius: 4px;
        }
        .bg-purple-dark {
            background: #99a9bf;
        }
        .bg-purple {
            background: #ffffff;
        }
        .bg-purple-light {
            background: #e5e9f2;
        }
        .grid-content {
            border-radius: 4px;
            min-height: 36px;
        }
        .row-bg {
            padding: 10px 0;
            background-color: #f9fafc;
        }
        ::v-deep .el-table th,
        ::v-deep .el-table td {
            text-align: center !important;
        }
        .page{
            margin-top: 20px;
            height: 50px;
            line-height: 50px;
            text-align: center;
        }
        .t{
            text-align: right;
        }

    </style>


</head>
<body>
<div id="d1">
    <el-row>
        <el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
        <el-col :span="16">
            <div class="grid-content bg-purple-light">
                <!--表格-->
                <el-table
                        :data="tableData"
                        border
                        :header-cell-style="headContent"
                        :cell-style = "contentData"
                        stripe
                        style="width: 100%">
                    <el-table-column
                            prop="sid"
                            label="学号"
                            width="150">
                    </el-table-column>
                    <el-table-column
                            prop="sname"
                            label="学生姓名"
                            width="120">
                    </el-table-column>
                    <el-table-column
                            prop="sex"
                            label="学生性别"
                            width="150">
                    </el-table-column>
                    <el-table-column
                            prop="age"
                            label="学生年龄"
                            width="150">
                    </el-table-column>
                    <el-table-column
                            prop="addr"
                            label="学生地址"
                            width="120">
                    </el-table-column>
                    <el-table-column
                            prop="cname"
                            label="所在班级">
                    </el-table-column>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            width="300">
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row)" type="primary" size="mini">修改</el-button>
                            <el-button @click="deleteStu(scope.row)" type="danger" size="mini">删除</el-button>
                            <el-button @click="addStu()" type="success" size="mini">添加</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-row>
                <el-col :span="8">
                    <div class="grid-content bg-purple-light">
                        <!--{{sname}}-->
                        <el-input
                                placeholder="请输入查询学生的关键字"
                                v-model="sname"
                                clearable>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple-light">
                        <!--{{addr}}-->
                        <el-input
                                placeholder="请输入查询住址的关键字"
                                v-model="addr"
                                clearable>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="1" offset="3"><div class="grid-content bg-purple-light t">
                    <el-button @click="search()" type="success" size="medium">查询列表</el-button>
                </div></el-col>
                <el-col :span="1" offset="2"><div class="grid-content bg-purple-light t">
                    <el-button @click="returnList()" type="success" size="medium">返回列表</el-button>
                </div></el-col>
            </el-row>
            <div class="page">
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="1000">
                </el-pagination>
            </div>

        </el-col>

        <el-col :span="4"><div class="grid-content bg-purple"></div></el-col>

    </el-row>

    <!-- Form 点击修改时 显示当前对应学生对象的值-->
    <el-dialog title="学生信息" :visible.sync="dialogFormVisible">
        {{student}}
        <el-form :model="student">
            <el-form-item label="学生姓名" :label-width="formLabelWidth">
                <el-input v-model="student.sname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="学生性别" :label-width="formLabelWidth">
                <el-radio v-model="student.sex" label=""></el-radio>
                <el-radio v-model="student.sex" label=""></el-radio>
            </el-form-item>
            <el-form-item label="学生年龄" :label-width="formLabelWidth">
                <el-input v-model="student.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="学生地址" :label-width="formLabelWidth">
                <el-input v-model="student.addr" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="所在班级" :label-width="formLabelWidth">
                <el-select v-model="student.cid" placeholder="请选择所在班级" style="width: 100%">
                    <el-option v-for="c in classes" :label="c.cname" :value="c.cid"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="save()">确 定</el-button>
        </div>
    </el-dialog>

</div>
</body>
<script>
    new Vue({
        el:"#d1",
        data:{
            tableData: [],  //查询所有学生
            dialogFormVisible: false, //默认弹出框不弹出
            student: {  //单个学生信息
                sname: '',
                sex: '',
                age: '',
                addr: '',
                cid: '',
            },
            formLabelWidth: '120px',
            classes:[], //查询所有班级信息
            sname:'',  //查询学生姓名关键字
            addr:'', //查询学生住址关键字
        },
        methods:{
            //1.定义查询所有学生的方法
            findAllStudents(){
                axios.get("student?cmd=list").then(response=>{  //找到servlet对应的方法 查询学生数据
                    //console.log(response);
                    this.tableData = response.data; //将后端传来的数据赋值给数组 属性必须一一对应
                })
            },
            //2.设置表头居中以及表格内容居中
            headContent(){
                return "text-align:center;color:blue;background:aqua";
            },
            contentData(){
                return "text-align:center";
            },
            //3.查询所有班级信息
            findAllClasses(){
                axios.get("class?cmd=list").then(response=>{
                    this.classes = response.data;
                })
            },
            //4.查看单个学生对象 点击表格修改
            handleClick(row){  //row表示当前这一行
                //console.log(row) //row表示当前这一行学生对象的值
                this.dialogFormVisible = true; //显示弹出框
                this.student = row; //将当前数据显示在弹出框页面当中
            },
            //5.添加学生
            addStu(){
                this.dialogFormVisible = true; //显示弹出框
                this.student = {}; //清空学生对象
            },
            //6.修改学生或者添加学生(保存学生)
            save(){
                //6.1)关闭对话框
                this.dialogFormVisible = false;
                //6.2)定义url
                let url = "student?cmd=add";
                //6.3)判断此时对话框中学生对象是否存在sid
                if(this.student.sid){
                    //6.4)执行修改
                    url = "student?cmd=update"
                }
                //6.5)执行后台操作
                axios.post(url,"stud="+JSON.stringify(this.student)).then(response=>{
                    console.log(response);
                    //6.5.1)获取后台传送的信息
                    if(response.data.success){
                        this.findAllStudents(); //说明数据添加或者修改成功 刷新页面
                    }else{
                        alert(response.data.message) //说明添加数据或者修改数据失败
                    }
                })
            },
            //7.删除学生
            deleteStu(row){
                this.student = row; //设置当前需要删除的对象
                //console.log(this.student.sid);
                //将需要删除的学生sid作为参数进行传入
                axios.get("student?cmd=delete&sid="+this.student.sid).then(response=>{
                    console.log(response);
                    //7.1)获取后台传送的信息
                    if(response.data.success){
                        this.findAllStudents(); //说明数据删除成功 刷新页面
                    }else{
                        alert(response.data.message) //说明数据删除失败
                    }
                })
            },
            //8.查询学生
            search(){
                //8.1)将需要查询的关键字传入后端
                axios.get("student?cmd=search&sname="+this.sname+"&addr="+this.addr).then(response=>{
                    console.log(response.data);
                    this.tableData = response.data; //返回后端查询的数据
                })
            },
            //9.返回列表
            returnList(){
                this.sname = "";
                this.addr = "";
                axios.get("student?cmd=list").then(response=>{  //找到servlet对应的方法 查询学生数据
                    this.tableData = response.data; //将后端传来的数据赋值给数组 属性必须一一对应
                })
            },
        },
        created(){  //创建vue实例后调用方法
            this.findAllStudents();
            this.findAllClasses();
        }
    })
</script>

2.5 后端

src目录下创建com.chrisfeng多重目录

2.5.1-pojo实体类:

  • Student(对应数据库中的学生表)

    package com.zelin.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {
        private int sid;
        private String sname;
        private String sex;
        private int age;
        private String addr;
        private int cid;
        private String cname;
        public Student(String sname,String sex,int age,String addr,int cid){
            this.sname = sname;
            this.sex = sex;
            this.age = age;
            this.addr = addr;
            this.cid = cid;
        }
        public Student(int sid,String sname,String sex,int age,String addr,int cid){
            this(sname,sex,age,addr,cid);
            this.sid = sid;
    
        }
    }
    
  • Classes(对应数据库中的班级表)

    package com.zelin.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Classes {
        private int cid;
        private String cname;
    }
    
  • **Result:**用于实现前端页面实现增删改的提示信息 success:true 表示成功 false:表示失败 message:返回信息

    package com.zelin.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @author wf
     * @date 2020-10-08 21:24
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Result {
        private boolean success;
        private String message;
    }
    

2.5.2 util工具包

JdbcUtil

package com.zelin.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;


public class JdbcUtil {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    public static DataSource getDataSource(){
        return dataSource;
    }
}

2.5.3 servlet:控制层

  • StudentServlet

    package com.zelin.servlet;
    
    
    import cn.hutool.core.util.StrUtil;
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.zelin.pojo.Result;
    import com.zelin.pojo.Student;
    import com.zelin.service.StudentService;
    import com.zelin.service.impl.StudentServiceImpl;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.List;
    
    
    /**
     * @author wf
     * @date 2020-10-08 19:57
     */
    @WebServlet("/student")
    public class StudentServlet extends HttpServlet {
        private StudentService studentService;
        @Override
        public void init() throws ServletException {
            studentService = new StudentServiceImpl();
        }
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.设置编码格式
            req.setCharacterEncoding("UTF8");
            resp.setContentType("text/html;charset=UTF8");
            //2.获取参数
            String cmd = req.getParameter("cmd");
            //3.判断参数 选择不同的方法
            if(StrUtil.isNotBlank(cmd)){
                if("list".equals(cmd)){
                    list(req,resp);
                }else if("add".equals(cmd)){
                    addStu(req,resp); //添加学生
                }else if("update".equals(cmd)){
                    update(req,resp); //修改学生
                }else if("delete".equals(cmd)){
                    delStu(req,resp); //删除学生
                }else if("search".equals(cmd)){
                    search(req,resp);
                }
            }
        }
    
        //2.查询所有学生
        private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
            try {
                //2.1)查询所有学生
                List<Student> studentList = studentService.findAll();
                //2.2)输出打印
                resp.getWriter().println(JSON.toJSONString(studentList));
                //2.3)刷新
                resp.getWriter().flush();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //3.添加学生
        private void addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
            //3.0)定义结果对象
            Result result = null;
            try {
                //3.1)获取前端传过来的参数
                String stud = req.getParameter("stud");
                //3.2)将json字符串转为学生对象
                Student student = JSON.parseObject(stud, Student.class);
                //3.3)将添加的学生数据添加到数据库中
                studentService.insert(student);
                //3.4)返回结果给前端
                result = new Result(true,"添加学生成功!");
            } catch (Exception e) {
                e.printStackTrace();
                result = new Result(false,"添加学生对象失败!");
            }
            //3.5)返回结果给前端页面
            resp.getWriter().println(JSON.toJSONString(result));
            //3.6)刷新页面
            resp.getWriter().flush();
        }
        //4.修改学生
        private void update(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
            //4.1)定义结果对象
            Result result = null;
            try {
                //4.2)获取前端传过来的参数
                String stud = req.getParameter("stud");
                //4.3)将json字符串转为学生对象
                Student student = JSON.parseObject(stud, Student.class);
                //4.4)将修改后的学生数据添加到数据库中
                studentService.update(student);
                //4.5)返回结果给前端
                result = new Result(true,"修改学生成功!");
            } catch (Exception e) {
                e.printStackTrace();
                result = new Result(false,"修改学生对象失败!");
            }
            //4.6)返回结果给前端页面
            resp.getWriter().println(JSON.toJSONString(result));
            //4.7)刷新页面
            resp.getWriter().flush();
        }
        //5.删除学生
        private void delStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //5.1)定义结果对象
            Result result = null;
            try {
                //5.2)获取前端传来的参数
                String sid = req.getParameter("sid");
                System.out.println("前端传过来的学生编号为:"+sid);
                //5.3)删除对应的学生
                studentService.delete(sid);
                //5.4)返回结果给前端
                result = new Result(true, "删除学生成功!");
            } catch (Exception e) {
                e.printStackTrace();
                result = new Result(false, "删除学生对象失败!");
            }
            //5.5)返回结果给前端页面
            resp.getWriter().println(JSON.toJSONString(result));
            //5.6)刷新页面
            resp.getWriter().flush();
        }
        //6.查询学生
        private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
            try {
                //6.1)获取前端传来的参数
                String sname = req.getParameter("sname");
                String addr = req.getParameter("addr");
                System.out.println("姓名关键字为:"+sname+"住址关键字为:"+addr);
                //6.2)传入数据库
                List<Student> students = studentService.search(sname,addr);
                //6.3)输出打印
                resp.getWriter().println(JSON.toJSONString(students));
                //6.4)刷新
                resp.getWriter().flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
    
  • ClassesServlet

    package com.zelin.servlet;
    
    import cn.hutool.core.util.StrUtil;
    import com.alibaba.fastjson.JSON;
    import com.zelin.pojo.Classes;
    import com.zelin.pojo.Student;
    import com.zelin.service.ClassesService;
    import com.zelin.service.impl.ClassServiceImpl;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 21:00
     */
    @WebServlet("/class")
    public class ClassesServlet extends HttpServlet {
        private ClassesService classesService;
        @Override
        public void init() throws ServletException {
            classesService = new ClassServiceImpl();
        }
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.设置编码格式
            req.setCharacterEncoding("UTF8");
            resp.setContentType("text/html;charset=UTF8");
            //2.获取参数
            String cmd = req.getParameter("cmd");
            //3.判断参数 选择不同的方法
            if(StrUtil.isNotBlank(cmd)){
                if("list".equals(cmd)){
                    list(req,resp);
                }
            }
        }
        //2.查询所有班级
        private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
            try {
                //2.1)查询所有学生
                List<Classes> classesList = classesService.findAll();
                //2.2)输出打印
                resp.getWriter().println(JSON.toJSONString(classesList));
                //2.3)刷新
                resp.getWriter().flush();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    

2.5.4 service:业务层

  • 定义接口

    ServiceStudent

    package com.zelin.service;
    
    import com.zelin.pojo.Student;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 20:06
     */
    public interface StudentService {
        List<Student> findAll() throws SQLException;
    
        void insert(Student student) throws SQLException;
    
        void update(Student student) throws SQLException;
    
        void delete(String sid) throws SQLException;
    
        List<Student> search(String sname, String addr) throws SQLException;
    }
    

    ClassesService

    package com.zelin.service;
    
    import com.zelin.pojo.Classes;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 21:02
     */
    public interface ClassesService {
        List<Classes> findAll() throws SQLException;
    }
    
  • impl:接口的实现类
    StudentServiceImpl

    package com.zelin.service.impl;
    
    import com.zelin.dao.StudentDao;
    import com.zelin.dao.impl.StudentDaoImpl;
    import com.zelin.pojo.Student;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 20:06
     */
    public class StudentServiceImpl implements com.zelin.service.StudentService {
        private StudentDao studentDao = new StudentDaoImpl();
        //1.查询所有学生
        @Override
        public List<Student> findAll() throws SQLException {
            return studentDao.findAll();
        }
        //2.添加学生
        @Override
        public void insert(Student student) throws SQLException {
            studentDao.insert(student);
        }
        //3.修改学生对象
        @Override
        public void update(Student student) throws SQLException {
            studentDao.update(student);
        }
        //4.删除学生
        @Override
        public void delete(String sid) throws SQLException {
            studentDao.delete(sid);
        }
        //5.关键字查询学生
        @Override
        public List<Student> search(String sname, String addr) throws SQLException {
            return studentDao.search(sname,addr);
        }
    }
    
    

    ClassesServiceImpl

    package com.zelin.service.impl;
    
    import com.zelin.dao.ClassesDao;
    import com.zelin.dao.impl.ClassesDaoImpl;
    import com.zelin.pojo.Classes;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 21:02
     */
    public class ClassServiceImpl implements com.zelin.service.ClassesService {
        private ClassesDao classesDao = new ClassesDaoImpl();
        @Override
        public List<Classes> findAll() throws SQLException {
            return classesDao.findAll();
        }
    }
    

2.5.5 dao:持久层 与数据库进行交互

  • dao层接口

    StudentDao

    package com.zelin.dao;
    
    import com.zelin.pojo.Student;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 20:14
     */
    public interface StudentDao {
        List<Student> findAll() throws SQLException;
    
        void insert(Student student) throws SQLException;
    
        void update(Student student) throws SQLException;
    
        void delete(String sid) throws SQLException;
    
        List<Student> search(String sname, String addr) throws SQLException;
    }
    

    ClassesDao

    package com.zelin.dao;
    
    import com.zelin.pojo.Classes;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 21:04
     */
    public interface ClassesDao {
        List<Classes> findAll() throws SQLException;
    }
    
  • dao层接口的实现

    StudentDaoImpl

    package com.zelin.dao.impl;
    
    import cn.hutool.core.util.StrUtil;
    import com.zelin.dao.StudentDao;
    
    import com.zelin.pojo.Student;
    import com.zelin.util.JdbcUtil;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 20:14
     */
    public class StudentDaoImpl implements StudentDao {
        private QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        //1.查询所有学生信息
        @Override
        public List<Student> findAll() throws SQLException {
            return runner.query("select st.*,cname from student st,classes c where c.cid = st.cid",
                    new BeanListHandler<>(Student.class));
        }
        //2.添加学生
        @Override
        public void insert(Student student) throws SQLException {
            runner.update("insert into student values(null,?,?,?,?,?)",
                    student.getSname(),student.getSex(),student.getAge(),
                    student.getAddr(),student.getCid());
        }
        //3.修改学生对象
        @Override
        public void update(Student student) throws SQLException {
            runner.update("update  student set sname=?,sex=?,age=?,addr=?,cid=? where sid=? ",
                    student.getSname(),student.getSex(),student.getAge(),
                    student.getAddr(),student.getCid(),student.getSid());
        }
        //4.删除学生
        @Override
        public void delete(String sid) throws SQLException {
            runner.update("delete from student where sid=?",sid);
        }
        //5.关键字查询学生
        @Override
        public List<Student> search(String sname, String addr) throws SQLException {
            String sql = "select st.*,cname from student st,classes c where c.cid = st.cid";
            if(StrUtil.isNotBlank(sname)){
                sql += " and sname like '%"+sname+"%'";
            }
            if(StrUtil.isNotBlank(addr)){
                sql += " and addr like '%"+addr+"%'";
            }
            System.out.println("SQL = "+sql);
            return runner.query(sql,new BeanListHandler<>(Student.class));
        }
    }
    
    

    ClassesDaoImpl

    package com.zelin.dao.impl;
    
    import com.zelin.dao.ClassesDao;
    import com.zelin.pojo.Classes;
    
    import com.zelin.util.JdbcUtil;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * @author wf
     * @date 2020-10-08 21:04
     */
    public class ClassesDaoImpl implements ClassesDao {
        private QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        @Override
        public List<Classes> findAll() throws SQLException {
            return runner.query("select * from classes ",
                    new BeanListHandler<>(Classes.class));
        }
    }
    

2.6 效果演示

Vue基本案例使用以及Vue+ElementUI+cp30连接池实现学生管理系统的增删改查

相关标签: JavaWeb java