SpringMVC学习笔记(五)--数据回显-->Ajax

目录

一、json交互原理

二、代码示例

2.1 目录结构

2.2 前奏--配置文件

2.3 核心--CRUD的编写

2.3.1 利用MyBatis的Mapper代理实现CRUD

2.3.2 Ajax的实现

2.3.3 结果演示

 


一、json交互原理

@RequestBody:将页面的json字符串-->Java对象

@ResponseBody:

  • 避免进入视图解析器
  • 将java对象 -->  json数据(jackson去实现转换)

 


二、代码示例

2.1 目录结构

我们此次写的是teacher表的CRUD

2.2 前奏--配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--在全局配置文件中指定db.properties文件的位置-->
    <properties resource="db.properties"></properties>
    <!--别名-->
    <typeAliases>
        <!-- 批量定义别名 -->
        <package name="com.jc.entity"/>
    </typeAliases>
    <!--配置数据源-->
    <environments default="development">
        <environment id="development">
            <!-- JDBC的事务,现在由Mybatis控制 -->
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!--指定映射文件位置-->
    <mappers>
        <!--批量加载-->
        <package name="com.jc.dao"></package>
    </mappers>
</configuration>

此处需要注意的是我们配的是*.do,不是之前 / 

2.3 核心--CRUD的编写

2.3.1 利用MyBatis的Mapper代理实现CRUD

Teacher.java

public class Teacher {
    private int tid;
    private String tname;
    private String sex;
    private String password;
    private int age;
//get、set方法
}

TeacherMapper.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">
<!-- 命名空间,可以对sql进行分类的一个管理 -->
<mapper namespace="com.jc.dao.TeacherMapper">
    <select id="findAll" resultType="Teacher">
        select tid,tname,sex,password,age from teacher
    </select>
    <insert id="addTeacher" parameterType="teacher">
        insert into teacher (tid,tname,sex,password,age) values (#{tid},#{tname},#{sex},#{password},#{age})
    </insert>
    <select id="findByTid" parameterType="int" resultType="teacher">
        select tid,tname,sex,password,age from teacher where tid=#{0}
    </select>
    <update id="updateTeacher" parameterType="teacher">
        update teacher set tname=#{tname},sex=#{sex},password=#{password},age=#{age}
        where tid=#{tid}
    </update>
    <delete id="deleteTeacher" parameterType="int">
        delete from teacher where tid=#{0}
    </delete>

</mapper>

TeacherMapper.java

public interface TeacherMapper {
    public List<Teacher> findAll();
    public void addTeacher(Teacher teacher);
    public Teacher findByTid(int tid);
    public void updateTeacher(Teacher teacher);
    public void deleteTeacher(int tid);
}

2.3.2 Ajax的实现

  • 查询全部(先通过发送index.do请求跳到页面,页面在文档就绪事件里调用Ajax查询全部信息)

后台:TeacherController.java

@Controller
@RequestMapping("teacher")
public class TeacherController {

    SqlSession sqlSession=null;
    TeacherMapper teacherMapper=null;
    Model model=null;
    public void before() throws IOException {
        //1、通过IO读取配置文件
        InputStream inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
        //2、创建会话工厂,传入Mybatis配置文件信息
        SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        //3、通过会话工厂获取会话
        sqlSession=sessionFactory.openSession(true);
        teacherMapper=sqlSession.getMapper(TeacherMapper.class);
    }
    public void after(){
        sqlSession.close();
    }

    //首页跳转
    @RequestMapping("index")
    public String index(){
        return "showTeacher";
    }

    //查询全部
    @RequestMapping("findAll")
    @ResponseBody
    public List<Teacher> findAll(Model model) throws IOException {
        before();
        List<Teacher> teacherList = teacherMapper.findAll();
        model.addAttribute("teacherList",teacherList);
        after();
        return teacherList;
    }
}

页面:showTeacher.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>展示教师</title>
</head>
<body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(function () {
        //查询全部
        $.ajax({
            type:'POST',
            url:'http://localhost:8080/springMVC/teacher/findAll.do',
            data:{},
            contentType:"application/json",
            success:function (data) {
                // alert(data);
                var table="<table border='1'><tr align='center'>" +
                    "<td></td><td>教师ID</td><td>教师姓名</td><td>教师性别</td><td>教师密码</td><td>教师年龄</td><td>操作</td></tr>";
                $.each(data,function (index,item) {
                    // alert(item.tid);
                    table+="<tr><td><input type='checkbox' value='${item.tid}'></td>" +
                        "<td><input value='"+item.tid+"' readonly='readonly'/></td>" +
                        "<td><input value='"+item.tname+"'/></td>" +
                        "<td><input value='"+item.sex+"'/></td>" +
                        "<td><input value='"+item.password+"'/></td>" +
                        "<td><input value='"+item.age+"'/></td>" +
                        "<td><button id='delete' tid='"+item.tid+"'>删除</button>" +
                        "<button id='modify' tid='"+item.tid+"'>修改</button></td></tr>";
                })
                table+="</table>";
                $("#show").append(table);
            },
            error:function () {
                alert("fail");
            }
        });
    })
</script>
</body>
</html>
  • 添加(页面添加add超链接到后台,后台接收请求跳转到添加页面,之后添加页面通过Ajax插入数据,然后刷新index.do的信息)

页面:showTeacher.jsp

后台:TeacherController.java

//添加跳转
    @RequestMapping("add")
    public String toJSP() {
        return "addTeacher";
    }

    //添加
    @RequestMapping("insert")
    @ResponseBody
    public void addTeacher(@RequestBody Teacher t) throws IOException {
        before();
        Teacher teacher=new Teacher();
        teacher.setTname(t.getTname());
        teacher.setSex(t.getSex());
        teacher.setPassword(t.getPassword());
        teacher.setAge(t.getAge());
        teacherMapper.addTeacher(teacher);
        after();
    }

页面:addTeacher.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>添加教师信息</title>
</head>
<body>
<div align="center">
    <label>教师姓名</label><input type="text" placeholder="教师姓名" id="a" name="tname" required="required"/><br><br>
    <label>教师性别</label><input type="text" placeholder="教师性别" id="b" name="sex" required="required"/><br><br>
    <label>教师密码</label><input type="text" placeholder="教师密码" id="c" name="password" required="required"/><br><br>
    <label>教师年龄</label><input type="text" placeholder="教师年龄" id="d" name="age" required="required"/><br><br><br>
    <button>确认添加</button>
</div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
    $("button").click(function () {
        // var tname=document.getElementById("a").value;
        var tname = document.getElementsByTagName("input")[0].value;
        var sex = document.getElementsByTagName("input")[1].value;
        var password = document.getElementsByTagName("input")[2].value;
        var age = document.getElementsByTagName("input")[3].value;
        var jstr={tname:tname,sex:sex,password:password,age:age};
        var jsonString=JSON.stringify(jstr);
        // alert(tname);
        $.ajax({
            type:'POST',
            url:'http://localhost:8080/springMVC/teacher/insert.do',
            data:jsonString,
            contentType:"application/json",
            success:function (data){
                window.location.href="http://localhost:8080/springMVC/teacher/index.do";
            }
        });
    });
</script>
</html>
  • 根据tid查询(点击编辑的时候,将查询结果弹窗显示,可供后续修改)

页面:showTeacher.jsp

  • 在body里将要弹出的页面放在div里面,并设置display:none
<!-- 弹窗修改信息 -->
<div id="showdiv" style="width: 40%; margin: 0 auto;  border: 1px solid #999; display: none; position: absolute; top: 20%; left: 30%; z-index: 3; background: #fff">
    <!-- 标题 -->
    <div style="background: #F8F7F7; width: 100%; height: 2rem; font-size: 0.65rem; line-height: 2rem; border: 1px solid #999; text-align: center;" >
        修改教师信息
    </div>
    <!-- 内容 -->
    <div id="content" style="text-indent: 50px; height: 20rem; font-size: 0.5rem; padding: 0.5rem; line-height: 1rem; ">

    </div>
    <!-- 按钮 -->
    <div style="background: #418BCA; width: 30%; margin: 0 auto; height: 1.5rem; line-height: 1.5rem; text-align: center;color: #fff;margin-top: 1rem; -moz-border-radius: .128rem; -webkit-border-radius: .128rem; border-radius: .128rem;font-size: .59733rem;" onclick="closeWindow()">
        确 定
    </div>
</div>
  • 点击修改按钮触发事件,将tid传过去查询信息,显示窗口(要事件委托) 
//事件委托//
    //修改
    $("body").on("click","#modify",function () {
        var attribute = this.getAttribute("tid");
        //弹窗显示教师信息并修改
        showWindow(attribute);
    });
  •  弹窗(Ajax查询信息,将查询结果追加到内容的div处并显示)
// 弹窗(查询教师信息)
    function showWindow(attribute) {
        var jstr={tid:attribute};
        var jsonString=JSON.stringify(jstr);
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/springMVC/teacher/findByTid.do',
            data: jsonString,
            contentType: "application/json",
            success: function (data) {
                // window.location.href = "http://localhost:8080/springMVC/teacher/index.do";
                var info=
                        "<label>教师ID</label><input type=\"text\"  placeholder=\"教师ID\"  value='"+data.tid+"' id=\"tid\" name=\"tid\"readonly=\"readonly\" required=\"required\"/><br><br>"+
                        "<label>教师姓名</label><input type=\"text\" placeholder=\"教师姓名\" value='"+data.tname+"' id=\"tname\" name=\"tname\" required=\"required\"/><br><br>" +
                        "<label>教师性别</label><input type=\"text\" placeholder=\"教师性别\" value='"+data.sex+"' id=\"sex\" name=\"sex\" required=\"required\"/><br><br>" +
                        "<label>教师密码</label><input type=\"text\" placeholder=\"教师密码\" value='"+data.password+"' id=\"password\" name=\"password\" required=\"required\"/><br><br>" +
                        "<label>教师年龄</label><input type=\"text\" placeholder=\"教师年龄\" value='"+data.age+"' id=\"age\" name=\"age\" required=\"required\"/><br><br><br>"
                // alert(data.tname);
                $('#content').empty();
                $('#content').append(info);
                $('#showdiv').show();  //显示弹窗
            }
        });
    }

 后台:TeacherController.java

//查询教师信息
    @RequestMapping("findByTid")
    @ResponseBody
    public Teacher findByTid(@RequestBody Teacher t) throws IOException {
        before();
        Teacher teacher = teacherMapper.findByTid(t.getTid());
        after();
        return teacher;
    }
  • 修改

页面:showTeacher.jsp

  • 当弹窗修改完点击“确定”的时候,即触发closeWindow函数,将结果保存
// 关闭弹窗(修改教师信息)
    function closeWindow() {
        $('#showdiv').hide();  //隐藏弹窗

        var tid = document.getElementById("tid").value;
        var tname = document.getElementById("tname").value;
        var sex = document.getElementById("sex").value;
        var password = document.getElementById("password").value;
        var age = document.getElementById("age").value;

        var jstr={tid:tid,tname:tname,sex:sex,password:password,age:age};
        var jsonString=JSON.stringify(jstr);
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/springMVC/teacher/update.do',
            data: jsonString,
            contentType: "application/json",
            success: function (data) {
                window.location.href = "http://localhost:8080/springMVC/teacher/index.do";
            }
        });
    }

后台:TeacherController.java

//修改
    @RequestMapping("update")
    @ResponseBody
    public void updateTeacher(@RequestBody Teacher teacher) throws IOException {
        before();
        teacher.setTid(teacher.getTid());
        teacher.setTname(teacher.getTname());
        teacher.setSex(teacher.getSex());
        teacher.setPassword(teacher.getPassword());
        teacher.setAge(teacher.getAge());
        teacherMapper.updateTeacher(teacher);
        after();
//        return "redirect:findAll.do";
    }
  • 删除

页面:showTeacher.jsp

//删除
    $("body").on("click","#delete",function () {
        if(confirm("确实要删除吗?")){
            var attribute = this.getAttribute("tid");
            // alert(attribute);
            var jstr={tid:attribute};
            var jsonString=JSON.stringify(jstr);
            $.ajax({
                type: 'POST',
                url: 'http://localhost:8080/springMVC/teacher/delete.do',
                data: jsonString,
                contentType: "application/json",
                success: function (data) {
                    alert("删除成功!");
                    window.location.href = "http://localhost:8080/springMVC/teacher/index.do";
                }
            });
        }
    });

后台:TeacherController.java

//删除
    @RequestMapping("delete")
    @ResponseBody
    public void deleteTeacher(@RequestBody Teacher teacher) throws IOException {
        before();
        teacherMapper.deleteTeacher(teacher.getTid());
        after();
    }

至此,Ajax实现CRUD功能已全部实现

2.3.3 结果演示

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值