Web第九次作业

模仿上课的案例,完成对新表的查询和分页,添加删除修改查询等功能

学生信息表

前端页面index2.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>查询出所有并分页控件显示</title>
  <link rel="stylesheet" href="js/element.css">
</head>
<body style="align:center">

<div id="app" style="width: 80%;align:center">
  <h1 align="center">学生信息</h1>
  <div id="app" align="center">
    <a href="stu_insert.html">新增学生</a>
  </div>
  <el-table
          :data="tableData.filter(data => !search || data.author.toLowerCase().includes(search.toLowerCase()))"
          style="width: 100%;align:center;font-size: 20px">
    <el-table-column
            label="序号"
            prop="id">
    </el-table-column>
    <el-table-column
            label="姓名"
            prop="name">
    </el-table-column>
    <el-table-column
            label="性别"
            prop="sex">
    </el-table-column>
    <el-table-column
            label="密码"
            prop="password">
    </el-table-column>
    <el-table-column
            label="年龄"
            prop="age">
    </el-table-column>
    <el-table-column
            align="right">
      <template slot="header" slot-scope="scope">
        <el-input
                v-model="search"
                size="mini"
                placeholder="输入关键字搜索"/>
      </template>
      <template slot-scope="scope">
        <el-button
                size="mini"
                @click="handleEdit(scope.row)">编辑</el-button>
        <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <p align="center">
    <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 5, 10, 20]"
            :page-size="pageSize"
            :total="total">
    </el-pagination>
  </p>
</div>

<!-- 引入组件库 -->
<script src="js/jquery.min.js"></script>
<script src="js/vue.js"></script>
<script src="js/element.js"></script>
<script src="js/axios-0.18.0.js"></script>


<script>
  new Vue({
    el:"#app",
    data: {
      search: '',
      currentPage: 1,
      pageSize: 3,
      total: null,
      tableData: []
    },
    methods: {
      handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.findAll();
        console.log(`每页 ${val} 条`);

      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.findAll();
        console.log(`当前页: ${val}`);

      },
      findAll:function () {
        var _this = this;
        axios.post('/findAllJsoon', {
        })
                .then(function (response) {
                  _this.stuList = response.data.data;//响应数据给tableData赋值
                })
                .catch(function (error) {
                  console.log(error);
                });
      },
      handleEdit(row) {
        window.location.href="stu_edit.html?id="+row.id;
      },
      handleDelete(row) {
        window.location.href="stu_delete.html?id="+row.id;
      },

      findAll() {

        var url = `/peom/${this.currentPage}/${this.pageSize}`

        axios.get(url)
                .then(res =>{
                  this.tableData = res.data.data.rows;
                  this.total=res.data.data.total;
                  console.log(this.tableData);
                  console.log(this.total);
                })
                .catch(error=>{
                  console.error(error);
                })
      }
    },
    created(){
      this.findAll();
    }
  })
</script>
</body>
</html>

后端代码

①StuController

package com.example.demo.demos.controller;

import com.example.demo.demos.pojo.PageBean;
import com.example.demo.demos.pojo.Result;
import com.example.demo.demos.pojo.Stu;
import com.example.demo.demos.service.StuPageService;
import com.example.demo.demos.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
public class StuController {
    @Autowired
    StuPageService stuPageService;

    @GetMapping("/peom/{page}/{pageSize}")

    public Result findAll(@PathVariable  Integer page,
                          @PathVariable  Integer pageSize){
        PageBean pageBean =  stuPageService.list(page,pageSize);
        return Result.seccess(pageBean);
    }
    @RequestMapping("/findAll")
    public List<Stu> findAll(){
        return stuPageService.findAll();
    }

    @RequestMapping("/findAllJsoon")
    public Result findAllJson(){
        return  Result.seccess(stuPageService.findAll()) ;
    }
    @RequestMapping("/deleteStu_url/{id}")
    public void deleteStu_url(@PathVariable("id") Integer id){
        stuPageService.deleteStu(id);
    }
    @RequestMapping("/stufindById/{id}")
    public Result stufindById(@PathVariable("id") Integer id) {
        return  Result.seccess(stuPageService.stufindById(id));
    }

    @RequestMapping("/stuupdate")
    public  Result updateStu(@RequestBody Stu stu){
        boolean r = stuPageService.updateStu(stu);

        if(r) {
            // 成功  code==1
            return Result.success();
        } else {
            // 失败  code==0
            return Result.erro("更新失败");
        }
    }

    @RequestMapping("/stuinsert")
    public Result insertUser(@RequestBody Stu stu){
        boolean result =stuPageService.insertUser(stu);
        if(result) {
            // 成功  code==1
            return Result.success();
        } else {
            // 失败  code==0
            return Result.erro("添加失败");

        }

    }
}

②StuMapper

package com.example.demo.demos.mapper;

import com.example.demo.demos.pojo.Stu;
import org.apache.ibatis.annotations.*;

import java.util.List;
@Mapper
public interface StuMapper {

    @Select("select * from stu")
    public List<Stu> list();
    @Select("select * from Stu")
    public List<Stu> findAll();

    @Delete("delete from stu where id=#{id}")
    public int deleteStu(Integer id);

    @Select("select * from stu where id=#{id}")
    public Stu stufindById(Integer ID);

    @Update("update stu set name=#{name},sex=#{sex},password=#{password},age=#{age}  where id=#{id} ")
    public  boolean updateStu(Stu stu);

    @Insert("insert into stu(name, sex, password, age) values (#{name}, #{sex}, #{password}, #{age})")
    public int insert(Stu stu);
}

③PageBean

package com.example.demo.demos.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageBean {
    private Long total;//总记录数
    private List rows;//数据列表
}

④Result

package com.example.demo.demos.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private Integer code;//响应码,1 代表成功; 0 代表失败
    private String msg;  //响应信息 描述字符串
    private Object data; //返回的数据


    public static Result success(){
        return new Result(1,"success",null);
    }

    public static Result seccess(Object data){
        return new Result(1,"success",data);
    }

    public static Result erro(String str){
        return new Result(1,str,null);
    }
}

⑤Stu

package com.example.demo.demos.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stu {
    private Integer id;
    private String name;
    private Integer password;
    private String sex;
    private Integer age;
}


⑥StuServiceB

package com.example.demo.demos.service.impl;

import com.example.demo.demos.mapper.StuMapper;
import com.example.demo.demos.pojo.PageBean;
import com.example.demo.demos.pojo.Stu;
import com.example.demo.demos.service.StuPageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StuServiceB implements StuPageService {
    @Autowired
    private StuMapper stuMapper;
    @Override
    public List<Stu> findAll() {
        return stuMapper.findAll();
    }

    @Override
    public int deleteStu(Integer id) {
        return stuMapper.deleteStu(id);
    }
    @Override
    public Stu stufindById(Integer id) {
        return stuMapper.stufindById(id);
    }

    @Override
    public boolean updateStu(Stu stu) {
        return stuMapper.updateStu(stu);
    }

    @Override
    public boolean  insertUser(Stu stu) {
        int result =  stuMapper.insert(stu);
        return result == 1;
    }
    @Override
    public PageBean list(Integer page,Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<Stu> stuList=stuMapper.list();
        PageInfo<Stu> p=new PageInfo<>(stuList);
        PageBean pageBean=new PageBean(p.getTotal(),p.getList());
        return pageBean;
    }
}

⑦StuPageService

package com.example.demo.demos.service;

import com.example.demo.demos.pojo.PageBean;
import com.example.demo.demos.pojo.Stu;

import java.util.List;

public interface StuPageService {
    public PageBean list(Integer page,Integer pageSize);

    public List<Stu> findAll();
    public int deleteStu(Integer id);

    public Stu stufindById(Integer id);

    public boolean updateStu(Stu stu);

    public   boolean  insertUser(Stu stu);

}

 

stu_insert.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
    <script src="./js/axios-0.18.0.js"></script>

</head>
<body>
<div id="app">
    <table border="1">

        <tr>
            <td>姓名</td>
            <td><input type="text" v-model="stu.name"> </td>
        </tr>
        <tr>
            <td>性别</td>
            <td>
                <input type="text" v-model="stu.sex">
            </td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="text" v-model="stu.password"> </td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" v-model="stu.age"> </td>
        </tr>

        <tr>
            <td></td>
            <td><input type="button" @click="addStu" value="增加"> </td>

        </tr>
    </table>

</div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            stu: {
                "name":"",
                "sex":"",
                "password":"",
                "age":""
            }        //详情

        },
        methods: {

            addStu() {
                var url = 'stuinsert'
                axios.post(url,this.stu)
                    .then(res => {
                        var baseResult = res.data
                        if(baseResult.code == 1) {
                            // 成功
                            location.href = 'index2.html'
                        } else {
                            // 失败
                            alert(baseResult.message)
                        }
                    })
                    .catch(err => {
                        console.error(err);
                    })
            }
        },

    })
</script>

</html>

 

stu_delete.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
    <script src="./js/axios-0.18.0.js"></script>

</head>
<body>
<div id="app" align="center">
            <td>
                <button type="button" @click="deleteId(stu.id)">删除</button>
                <a :href="'stu_delete.html?id='+stu.id">删除</a>
                <a :href="'stu_edit.html?id='+stu.id">修改</a>
            </td>
        </tr>

    </table>
</div>

</body>

<script>
    new Vue({
        el:"#app",
        data() {
            return {
                stuList:[]
            }
        },

        methods:{
            findAll:function () {
                var _this = this;
                axios.post('/findAllJsoon', {
                })
                    .then(function (response) {
                        _this.stuList = response.data.data;//响应数据给peotList 赋值
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            deleteId:function (id) {
                var _thisd = this;
                var url = `deleteStu_url/${this.id}`  //注意这里是反引号
                if (window.confirm("确定要删除该条数据吗???")){
                    axios.post(url)
                        .then(function (response) {
                            alert("删除成功")
                            // _thisd.findAll();
                            location.href = 'index2.html'
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            }

        },
        created() {
            // 获得参数id值
            this.id = location.href.split("?id=")[1]
            // 通过id查询详情
            this.deleteId();
        },
    })


</script>

</html>

 

stu_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生数据修改</title>
    <script src="./js/vue.js"></script>
    <script src="./js/axios-0.18.0.js"></script>

</head>
<body>
<div id="app">
    <table border="1">
        <tr>
            <td>编号</td>
            <td><input type="text" v-model="this.id"> </td>
        </tr>
        <tr>
            <td>姓名</td>
            <td><input type="text" v-model="stu.name"> </td>
        </tr>
        <tr>
            <td>性别</td>
            <td>
                <input type="text" v-model="stu.sex">
            </td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="text" v-model="stu.password"> </td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" v-model="stu.age"> </td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" @click="updateStu" value="更新"> </td>

        </tr>
    </table>
    {{stu}}
</div>


</body>
<script>
    new Vue({
        el: '#app',
        data: {
            id: '',
            stu: {},        //详情
        },
        methods: {
            selectById() {
                //${this.id}
                var url = `stufindById/${this.id}`  //注意这里是反引号
                //反引号(backticks,也称为模板字符串或模板字面量)是ES6(ECMAScript 2015)中引入的一种新字符串字面量功能,
                // 它允许您在字符串中嵌入表达式。反引号用`(键盘上通常位于Tab键上方)来界定字符串的开始和结束。
                axios.get(url)
                    .then(response => {
                        var baseResult = response.data
                        if(baseResult.code == 1) {
                            this.stu = baseResult.data
                        }
                    })
                    .catch( error => {})
            },
            updateStu() {
                var url = 'stuupdate'
                axios.put(url,this.stu)
                    .then(res => {
                        var baseResult = res.data
                        if(baseResult.code == 1) {
                            // 成功
                            location.href = 'index2.html'
                        } else {
                            // 失败
                            alert(baseResult.message)
                        }
                    })
                    .catch(err => {
                        console.error(err);
                    })
            },


        },
        created() {
            // 获得参数id值
            this.id = location.href.split("?id=")[1]
            // 通过id查询详情
            this.selectById()
        },

    })



</script>

</html>

 

 

采用XML映射文件的形式来映射sql语句

xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.PoetMapper">
    <!-- 查询 -->
    <select id="list" resultType="com.example.demo.pojo.Poet">
        select * from poet
    </select>
    <!-- 条件分页查询 -->
    <select id="list_chaxun" resultType="com.example.demo.pojo.Poet" parameterType="java.lang.String">
        select * from poet
        <where>
            <if test="name != null and name != ''">
                name like concat('%',#{name},'%')
            </if>
            <if test="style != null and style != ''">
                and style like concat('%',#{style},'%')
            </if>
        </where>
    </select>
</mapper>

PoetXmlController

package com.example.demo.controller;

import com.example.demo.pojo.PageBean;
import com.example.demo.pojo.Result;
import com.example.demo.service.PoetFenyeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/peoms")
public class PoetXmlController {
    @Autowired
private PoetFenyeService poetFenyeService;
    //条件分页查询
    @GetMapping("/{page}/{pageSize}")
    public Result page(@PathVariable Integer page,
                       @PathVariable Integer pageSize,
                       String name,
                       String style) {
        //记录日志
        log.info("分页查询,参数:{},{},{},{},{},{}", page, pageSize,name, style);
        //调用业务层分页查询功能
        PageBean pageBean = poetFenyeService.list_chaxun(page, pageSize, name, style);
        //响应
        return Result.success(pageBean);
    }

}

index6.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>xml方式写sql</title>
  <link rel="stylesheet" href="js/element.css">
</head>
<body style="align:center">

<div id="app" style="width: 80%;align:center">
  <h1 align="center">诗人信息</h1>
  <p align="center">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="formInline.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="风格">
        <el-input v-model="formInline.style" placeholder="风格"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
  </p>
  <el-table
          :data="tableData.filter(data => !search || data.author.toLowerCase().includes(search.toLowerCase()))"
          style="width: 100%;align:center;font-size: 20px">
    <el-table-column
            label="id"
            prop="id">
    </el-table-column>
    <el-table-column
            label="姓名"
            prop="name">
    </el-table-column>
    <el-table-column
            label="朝代"
            prop="dynasty">
    </el-table-column>
    <el-table-column
            label="头衔"
            prop="title">
    </el-table-column>
    <el-table-column
            label="风格"
            prop="style">
    </el-table-column>
    <el-table-column
            align="right">
      <template slot="header" slot-scope="scope">
        <el-input
                v-model="search"
                size="mini"
                placeholder="输入关键字搜索"/>
      </template>
      <template slot-scope="scope">
        <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
        <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
      </template>
    </el-table-column>
  </el-table>
  <p align="center">
    <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 5, 10, 20]"
            :page-size="pageSize"
            :total="total">
    </el-pagination>
  </p>
</div>

<!-- 引入组件库 -->
<script src="js/jquery.min.js"></script>
<script src="js/vue.js"></script>
<script src="js/element.js"></script>
<script src="js/axios-0.18.0.js"></script>


<script>
  new Vue({
    el:"#app",
    data: {
      search: '',
      currentPage: 1,
      pageSize: 4,
      total: null,
      tableData: [],
      formInline: {
        name: '',
        style: ''
      }
    },
    methods: {
      handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.findAll();
        console.log(`每页 ${val} 条`);

      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.findAll();
        console.log(`当前页: ${val}`);

      },
      onSubmit() {

        var url = `/peoms/${this.currentPage}/${this.pageSize}?name=${encodeURIComponent(this.formInline.name)}&style=${encodeURIComponent(this.formInline.style)}`

        console.log(this.formInline.name);
        console.log(this.formInline.style);


        axios.get(url)
                .then(res =>{
                  this.tableData = res.data.data.rows;
                  this.total=res.data.data.total;
                  console.log(this.tableData);
                  console.log(this.total);
                })
                .catch(error=>{
                  console.error(error);
                })

      },

      findAll() {

        var url = `/peoms/${this.currentPage}/${this.pageSize}`

        axios.get(url)
                .then(res =>{
                  this.tableData = res.data.data.rows;
                  this.total=res.data.data.total;
                  console.log(this.tableData);
                  console.log(this.total);
                })
                .catch(error=>{
                  console.error(error);
                })

      }

    },
    created(){
      this.findAll();
    }

  })


</script>

</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值