SpringMVC支持AJAX(响应JSON数据)

发布时间 2023-10-06 23:23:40作者: 空嘘一场

 

1.主要注解

 

2.整合Demo

1) ajax.jsp

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jacke
 4   Date: 2023/9/15
 5   Time: 16:40
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>SpringMVC 支持AJAX</title>
12     <script src="js/jquery.js"></script>
13     <script>
14         $(document).ready(function (){//绑定onload事件
15             //绑定按钮点击事件
16             $("#send").click(function (){
17                 //向服务器发送AJAX请求(参数1:url 参数2:JSON格式对象 参数3:回调函数(接受响应数据))
18                 $.getJSON("ajax",{
19                     username:$("#username").val(),
20                     content:$("#content").val()
21                 },function (commentDto){
22                     console.log(commentDto)//控制台打印
23                     //将返回的数据渲染到页面中
24                     let comment=$("<div></div>")
25                     comment.append(commentDto.username+":"+commentDto.content)
26                     $("#resText").append(comment)
27                 })
28             })
29         })
30 
31     </script>
32 </head>
33 <body>
34     <form>
35         <p>评论</p>
36         <P>姓名<input type="text" name="username" id="username"></P>
37         <p>内容:<textarea name="content" id="content" rows="3" cols="20"></textarea> </p>
38         <p> <input type="button" id="send" value="提交"></p>
39     </form>
40     <div class="comment">已有评论:</div>
41     <div id="resText"/>
42 </body>
43 </html>

2) AjaxController.java

 

 1 package com.cn.ajxa;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestBody;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.ResponseBody;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 /**
10  * @Author hxy
11  * @Description Ajax 页面控制器
12  * @Date 2023/9/18 11:15
13  * @Version 1.0
14  */
15 @RestController//等价于@Controller+@ResponseBody(该类的所有方法都是AJAX请求/响应)
16 public class AjaxController {
17     @RequestMapping("/ajax")//@RequestBody:将请求的JSOn格式数据转化为java对象
18 //    @ResponseBody//该注解将返回的java对象转化为JSON格式数据(字符串)
19     public CommentDto ajax(CommentDto commentDto){
20         System.out.println(commentDto);
21         return commentDto;//返回JSON格式数据
22     }
23 }