15.SpringMVC的Ajax

15. SpringMVC的Ajax

@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来向异步请求返回JSON数据。

注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。

(1)添加jacksonjar包

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.1</version>
</dependency>

(2)利用jQuery来实现Ajax异步请求

<%--
  Created by IntelliJ IDEA.
  User: God_86
  Date: 2020/6/29
  Time: 21:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>填写用户信息</title>
    <script type="text/javascript" src="${path}/statics/js/jQuery3.5.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#submitBtn").click(function () {
                $.post("${path}/userController/userSave",$('#formID').serialize(),function (data) {
                    alert(data.userName)
                })
            })
        })

    </script>
</head>

<body>
<form id="formID">
    用户名:<input type="text" name="userName">
    <br/>
    密码:<input type="password" name="password">
    <input type="button" value="提交" id="submitBtn">
</form>
</body>
</html>

(3)写处理方法

    @RequestMapping(value = "/userSave")
    @ResponseBody   //将返回的内容以流的形式响应 == resp.getWriter().print("");
    //springMVC异步返回结果时,是以json格式返回的
    public User userSave(User user, HttpSession session){
        System.out.println(user.getUserName());
        System.out.println(user.getPassword());
        System.out.println(user.getRegTime());
        return user;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值