学生管理系统VueAjax版本

学生管理系统VueAjax版本

使用Vue和Ajax对原有学生管理系统进行优化

1.准备工作

创建AjaxResult类,对Ajax回传的信息封装在对象中

java 复制代码
package com.grg.Result;

/**
 * @Author Grg
 * @Date 2023/8/30 8:51
 * @PackageName:com.grg.Result
 * @ClassName: AjaxResult
 * @Description: 又是码代码的一天
 * @Version plus max 宇宙无敌终极版本
 */
public class AjaxResult {
    private Integer code;
    private String msg;
    private Object data;

    public static AjaxResult success() {
        return new AjaxResult(1, "成功", null);
    }

    public static AjaxResult success(Object data) {
        return new AjaxResult(1, "成功", data);
    }

    public static AjaxResult error() {
        return new AjaxResult(2, "失败", null);
    }

    public AjaxResult() {
    }

    public AjaxResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    @Override
    public String toString() {
        return "AjaxResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

JDBC工具类DAOUtil

java 复制代码
package com.grg.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Grg
 * @Date 2023/8/26 14:35
 * @PackageName:com.grg.util
 * @ClassName: DAOUtil
 * @Description: 又是码代码的一天
 * @Version plus max 宇宙无敌终极版本
 */
public class DAOUtil {
    //消除魔法值
    private static final String CLASSNAME = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql:///jdbctest";
    private static final String USERNAME = "root";
    private static final String PASSWORDS = "123456";

    //加载驱动
    static {
        try {
            Class.forName(CLASSNAME);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //建立连接
    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(URL, USERNAME, PASSWORDS);
    }


    //增删改
    public static int executeUpdate(String sql, Object... data) {
        Connection conn = null;
        try {
            conn = DAOUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);

            for (int i = 0; i < data.length; i++) {
                ps.setObject(i + 1, data[i]);
            }

            return ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    //查
    public static List<Map<String, Object>> executeQuery(String sql, Object... arr) {

        List<Map<String, Object>> data = new ArrayList<>();
        Connection conn = null;
        try {
            conn = DAOUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                ps.setObject(i + 1, arr[i]);
            }
            ResultSet set = ps.executeQuery();
            int columnCount = set.getMetaData().getColumnCount();
            while (set.next()) {
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 0; i < columnCount; i++) {
                    map.put(set.getMetaData().getColumnLabel(i + 1), set.getObject(i + 1));
                }
                data.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }
}

pom文件

java 复制代码
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>StudentVue</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>StudentVue Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.33</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>2.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>StudentVue</finalName>
  </build>
</project>

2.登录模块

登录页面(默认页面)index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style>
        fieldset {
            margin: 100px auto;
            width: 500px;
        }
    </style>

</head>
<body>
<div id="app">
    <fieldset>
        <legend>登录</legend>
        <span class="label label-danger">{{msg}}</span>
        <div class="form-group">
            <label>UserName</label>
            <input class="form-control" placeholder="请输入账号" v-model="info.username">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" placeholder="请输入密码" v-model="info.password">
        </div>
        <button type="submit" class="btn btn-danger btn-block" @click="login()">登录</button>
    </fieldset>
</div>

<script>
    var haha = new Vue({
        el: "#app",
        data: {
            info: {},
            msg: "",
        },
        methods: {
            login: function () {
                //数据校验
                //发送请求
                $.post("/day/emp/login", haha.info, function (backData) {
                    if (backData.code == 1) {
                        //跳转主界面
                        window.location.href = "/day/main.html"
                    } else {
                        //显示失败信息
                        haha.msg = "对不起账号或密码错误"
                    }
                })
            }
        }
    })
</script>
</body>
</html>

对/day/emp/login发送post请求,查询数据并且回传

EmpServlet类 拦截到/emp/*的请求并进行处理

创建dao层 EmpDAO类和EmpDAOImpl实现类 实现对数据库中数据进行账号密码验证

EmpDAO接口

java 复制代码
public interface EmpDAO {
    List<Map<String,Object>> login(String username, String password);
}

EmpDAO实现类

java 复制代码
public class EmpDAOImpl implements EmpDAO {
    @Override
    public List<Map<String, Object>> login(String username, String password) {
        String sql = "select * from login where username = ? and password = ? ";
        return DAOUtil.executeQuery(sql, username, password);
    }
}

EmpServlet类

java 复制代码
package com.grg.servlet;

import com.alibaba.fastjson.JSON;
import com.grg.Result.AjaxResult;
import com.grg.dao.EmpDAO;
import com.grg.dao.impl.EmpDAOImpl;

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.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @Author Grg
 * @Date 2023/8/30 8:49
 * @PackageName:com.grg.servlet
 * @ClassName: EmpServlet
 * @Description: 又是码代码的一天
 * @Version plus max 宇宙无敌终极版本
 */
@WebServlet("/emp/*")
public class EmpServlet extends HttpServlet {
    private EmpDAO empDAO = new EmpDAOImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //路径分发
        String uri = req.getRequestURI();
        String[] arr = uri.split("/");
        String s = arr[arr.length - 1];

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        AjaxResult ajaxResult = null;

        if ("login".equals(s)) {
            ajaxResult = login(req, resp);
        }

        String s1 = JSON.toJSONString(ajaxResult);
        out.write(s1);
    }


    protected AjaxResult login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.校验账号密码
        List<Map<String, Object>> data = empDAO.login(username, password);

        if (data.size() > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}

当账号密码错误时,响应 {"code":2,"msg":"失败"}

当账号密码正确时,进入main.html

java 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>信息管理系统</title>

    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style>
        body {
            background: url('./img/reg_bg_min.jpg') no-repeat;
            background-size: 100% 100%;
        }

        a {
            text-decoration: none;
            color: white;
        }

        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }

        #header {
            background-color: #000000;
            /*color: #ffffff;*/
            padding: 10px;
            display: flex;
            justify-content: space-between;
        }

        #header h1, #header p {
            margin: 0;
        }

        #sidebar {
            /*background-color: #e1e1e1;*/
            width: 200px;
            height: 100vh;
            float: left;
        }

        #content {
            padding: 20px;
            margin-left: 200px;
        }

        #footer {
            /*background-color: #f5f5f5;*/
            padding: 10px;
            clear: both;
        }

        .menu-item {
            padding: 10px;
            margin-top: 10px;
        }

        .menu-item:hover {
            background-color: #d1d1d1;
        }

        #iframe-container {
            width: calc(100% - 20px);
            height: calc(100vh - 20px);
        }

        #iframe-content {
            width: 100%;
            height: 100%;
            border: none;
        }

    </style>
</head>
<body>
<div id="header">
    <!-- 学生管理系统的Logo和标题 -->
    <h1 style="color:white;">信息管理系统</h1>
    <!-- 用户信息和注销按钮 -->
    <p style="color:white;">当前登录用户:</p>

</div>
<div id="sidebar">
    <!-- 左侧菜单 -->
    <div class="menu-item">
        <a target="haha" href="/day/views/student/list.html">学生管理</a>
    </div>
    <div class="menu-item">
        <a target="haha" href="/teacher/show">教师管理</a>
    </div>
    <div class="menu-item">
        <a target="haha" href="/class/show">班级管理</a>
    </div>
    <div class="menu-item">
        <a target="haha" href="/views/emp/changepassword.jsp">修改密码</a>
    </div>
    <div class="menu-item">
        <a target="haha" href="/log">日志记录</a>
    </div>
    <div class="menu-item">
        <a href="/">注销</a>
    </div>
</div>
<div id="content">
    <div id="iframe-container">
        <iframe name="haha" src="" id="iframe-content"></iframe>
    </div>

</div>
<div id="footer">
    <!--     页面底部区域,可根据需求添加内容 -->
    <p style="color:white;">版权所有 &copy; 2023 学生管理系统</p>
</div>
</body>
</html>

3.学生管理

3.1查询学生

点击学生管理获取学生数据并且展示在页面上

java 复制代码
<a target="haha" href="/day/views/student/list.html">学生管理</a>

创建list.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="app">
    <a href="/day/views/student/add.html" class="btn btn-success">添加学生</a>

    <table class="table table-bordered table-condensed table-striped">
        <tr>
            <th>编号</th>
            <th>姓名</th>
        </tr>

        <tr v-for="(s,i) in stuArr">
            <td>{{s.id}}</td>
            <td>{{s.name}}</td>
            <td>
                <button class="btn btn-danger" @click="delStu(s.id)">删除</button>
                <button class="btn btn-primary">修改</button>
            </td>
        </tr>

    </table>
</div>

<script>

    $.get("/day/stu/list", function (backData) {
        haha.stuArr = backData.data;
    })

    var haha = new Vue({
        el: "#app",
        data: {
            stuArr: []
        },
        methods: {
            delStu: function (a) {
                if (confirm("确定删除?")) {
                    $.get("/day10/stu/delete?id=" + a, function (backDate) {
                        if (backDate.code == 2) {
                            alert("删除失败")
                        } else {
                            window.location.reload();
                        }
                    })
                }
            }
        }
    });
</script>
</body>
</html>

进入页面后通过ajax获取学生数据,并把返回的数据存入haha.stuArr数组中

javascript 复制代码
$.get("/day/stu/list", function (backData) {
        haha.stuArr = backData.data;
    })

/day/stu/list执行list函数

创建StudentServlet类、StudentDAO接口、StudentDAOImpl实现类

StudentDAO接口

java 复制代码
public interface StudentDAO {
    public List<Map<String, Object>> listAllStudent();

    public int deleteStudentById(String id);
}

StudentDAOImpl实现类

java 复制代码
public class StudentDAOImpl implements StudentDAO {
    @Override
    public List<Map<String, Object>> listAllStudent() {
        String sql = "select s.id,s.name from student s";
        return DAOUtil.executeQuery(sql);
    }

    @Override
    public int deleteStudentById(String id) {
        String sql = "delete from student where id = ? ";
        return DAOUtil.executeUpdate(sql, id);
    }
}

StudentServlet类

java 复制代码
package com.grg.servlet;

import com.alibaba.fastjson.JSON;
import com.grg.Result.AjaxResult;
import com.grg.dao.StudentDAO;
import com.grg.dao.impl.StudentDAOImpl;

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.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * @Author Grg
 * @Date 2023/8/30 8:49
 * @PackageName:com.grg.servlet
 * @ClassName: StudentServlet
 * @Description: 又是码代码的一天
 * @Version plus max 宇宙无敌终极版本
 */
@WebServlet("/stu/*")
public class StudentServlet extends HttpServlet {
    private StudentDAO studentDAO = new StudentDAOImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String[] arr = uri.split("/");
        String s = arr[arr.length - 1];

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        AjaxResult ajaxResult = null;

        if ("list".equals(s)) {
            ajaxResult = list(req, resp);
        } else if ("delete".equals(s)) {
            ajaxResult = delete(req, resp);
        }
        String s1 = JSON.toJSONString(ajaxResult);
        out.write(s1);
    }

    protected AjaxResult list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String, Object>> list = studentDAO.listAllStudent();
        return AjaxResult.success(list);
    }

    protected AjaxResult delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        int i = studentDAO.deleteStudentById(id);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}

3.2删除学生

点击删除按钮 执行点击事件函数delStu

在StudentServlet中执行删除

html 复制代码
<button class="btn btn-danger" @click="delStu(s.id)">删除</button>
js 复制代码
 methods: {
            delStu: function (a) {
                if (confirm("确定删除?")) {
                    $.get("/day/stu/delete?id=" + a, function (backDate) {
                        if (backDate.code == 2) {
                            alert("删除失败")
                        } else {
                            window.location.reload();
                        }
                    })
                }
            }
        }

3.3添加学生

html 复制代码
<a href="/day/views/student/add.html" class="btn btn-success">添加学生</a>

add.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<style>
    fieldset {
        width: 500px;
        margin: 100px auto;
    }
</style>
<body>

<div id="app">
    <fieldset>
        <legend>添加学生
            <span class="label label-primary"></span>
        </legend>

        <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">学生姓名</label>
            <div class="col-sm-10">
                <input name="name" v-model="stuInfo.name" type="text" class="form-control" id="inputEmail3"
                       placeholder="请输入学生姓名">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">学生年龄</label>
            <div class="col-sm-10">
                <input name="age" v-model="stuInfo.age" type="text" class="form-control" id="inputPassword3"
                       placeholder="请输入学生年龄">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">学生住址</label>
            <div class="col-sm-10">
                <select name="address" v-model="stuInfo.address">
                    <option>北京</option>
                    <option>郑州</option>
                    <option>上海</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">学生班级</label>
            <div class="col-sm-10">
                <select name="address" v-model="stuInfo.gid">
                    <option value="1">一年级</option>
                    <option value="2">二年级</option>
                    <option value="3">三年级</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default btn-success" @click="add()">添加</button>
            </div>
        </div>
    </fieldset>
</div>

<script>

    var haha = new Vue({
        el: "#app",
        data: {
            stuInfo: {},
        },
        methods: {
            add: function () {
                $.post("/day/stu/addStu", haha.stuInfo, function (backData) {
                })
            }
        }
    })
</script>
</body>
</html>

执行添加操作,在StudentServlet中执行addStu函数,并且编写DAO层相应添加函数

javascript 复制代码
$.post("/day/stu/add", haha.stuInfo, function (backData) {
java 复制代码
@Override
    public int addStu(Student student) {
        String sql = "insert into student values (null,?,?,?,?)";
        return DAOUtil.executeUpdate(sql,student.getName(),student.getAge(),student.getAddress(),student.getGid());
    }
java 复制代码
protected AjaxResult addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String address = req.getParameter("address");
        String gid = req.getParameter("gid");

        Student student = new Student(name, age,address,Integer.parseInt(gid));
        int i = studentDAO.addStu(student);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

3.4修改学生

点击修改按钮执行点击事件updateStu函数

<button class="btn btn-primary" @click="updateStu(s.id)">修改</button>
javascript 复制代码
updateStu: function (a) {
                window.location.href = "/day/views/student/update.html?id=" + a;
            }

update.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<style>
    fieldset {
        width: 500px;
        margin: 100px auto;
    }

    .col-sm-10 {
        width: 85.333333%;
    }

    .btn-block {
        width: 63%;
    }
</style>
<body>
<div id="app">
    <fieldset>

        <legend>修改学生
            <span class="label label-primary">{{msg}}</span>
        </legend>

        <div>
            <label class="col-sm-2 control-label">姓名</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="stuInfo.name">

            </div>
        </div>

        <div>
            <label class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="stuInfo.age">
            </div>
        </div>

        <div>
            <label class="col-sm-2 control-label">住址</label>
            <div class="col-sm-10">
                <select name="address" v-model="stuInfo.address">
                    <option>北京</option>
                    <option>郑州</option>
                    <option>上海</option>
                </select>
            </div>
        </div>

        <div>
            <label class="col-sm-2 control-label">班级</label>
            <div class="col-sm-10">
                <select name="gid" v-model="stuInfo.gid">
                    <option value="1">一年级</option>
                    <option value="2">二年级</option>
                    <option value="3">三年级</option>
                </select>
            </div>
        </div>

        <div>
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-info btn-block" @click="update()">修改</button>
                <a href="/day/views/student/list.html" class="btn btn-info btn-block">返回</a>
            </div>
        </div>
    </fieldset>
</div>

<script>

    var id = window.location.href.split("=")[1];
    $.get("/day/stu/getStu?id=" + id, function (backData) {
        haha.stuInfo = backData.data;
    })

    var haha = new Vue({
        el: "#app",
        data: {
            stuInfo: {},
            msg:""
        },
        methods: {
            update: function () {
                $.post("/day/stu/updateStu",haha.stuInfo,function (backData) {
                    haha.msg = backData.msg;
                })
            }
        }
    })
</script>
</body>
</html>

先发送请求到getStu

java 复制代码
protected AjaxResult getStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        List<Map<String, Object>> data = studentDAO.getStudentById(id);

        if (data.size() > 0) {
            return AjaxResult.success(data.get(0));
        } else {
            return AjaxResult.error();
        }
    }

点击修改按钮发送请求到updateStu

java 复制代码
protected AjaxResult updateStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String address = req.getParameter("address");
        String gid = req.getParameter("gid");
        String id = req.getParameter("id");

        Student student = new Student(Integer.parseInt(id), name, age, address, Integer.parseInt(gid));
        int i = studentDAO.updateStu(student);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();

    }
相关推荐
激流丶9 分钟前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue13 分钟前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
让学习成为一种生活方式29 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画35 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin
子非鱼9211 小时前
【Ajax】跨域
javascript·ajax·cors·jsonp
超雄代码狂1 小时前
ajax关于axios库的运用小案例
前端·javascript·ajax
秋意钟1 小时前
MySQL日期类型选择建议
数据库·mysql
孤客网络科技工作室1 小时前
AJAX 全面教程:从基础到高级
android·ajax·okhttp
南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
Heavydrink1 小时前
HTTP动词与状态码
java