Springmvc完成ajax功能实例详解
作者:游吟灬夏 时间:2021-09-07 23:23:25
1.加入jackson的jar包
2.在响应的方法上加上@ResponseBody:把java对象转化为json对象
3.方法的返回值可以是对象集合字符串
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$.post("ajax/Ajax1",{"name":"zhu"},function(data){
$.each(data,function(i,n){
alert(n.name);
})
})
</script>
可以返回字符串
@RequestMapping(value="Ajax1",produces = "text/html;charset=UTF-8")
@ResponseBody
public String ajax1(String name) {
System.out.println(name);
return "hello胡";
}
也可以返回对象
@RequestMapping("Ajax2")
@ResponseBody
public User ajax2(String name) {
User user=new User("胡昊中","1");
return user;
}
还可以返回集合
@RequestMapping("Ajax3")
@ResponseBody
public List<User> ajax3(String name) {
User user1=new User("胡昊中","1");
User user2=new User("朱华龙","2");
User user3=new User("王玉峰","3");
List<User> list=new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
在返回字符串时,如果输入汉字会出现乱码,解决方法如下
1. 更改@RequestMapping
@RequestMapping(value="Ajax1",produces="text/html;charset=UTF-8")
2. 在springMVC配置文件中通过org.springframework.web.servlet.view.InternalResourceViewResolver类重写代码编码。
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" value="utf-8"></constructor-arg>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
来源:https://www.cnblogs.com/zfyyfw/p/11456286.html
标签:Springmvc,ajax
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈JVM中的JOL
2022-10-06 15:44:49
SpringBoot注解梳理(小结)
2023-11-10 13:27:19
详解JAVA中的OPTIONAL
2022-08-22 17:09:04
![](https://img.aspxhome.com/file/2023/1/64001_0s.png)
Java实现断点下载服务端与客户端的示例代码
2022-07-25 14:16:17
Mybatis-Plus 全局配置无效的解决方案
2022-06-29 12:46:02
java多线程模拟抢红包功能
2023-07-25 01:09:58
解决jasperreport导出的pdf每页显示的记录太少问题
2023-04-14 13:02:01
![](https://img.aspxhome.com/file/2023/0/77080_0s.jpg)
使用eclipse创建java项目的方法
2022-10-15 04:41:00
![](https://img.aspxhome.com/file/2023/0/64010_0s.jpg)
浅谈redis key值内存消耗以及性能影响
2022-11-09 20:35:17
C#简单输出日历的方法
2023-11-13 05:56:10
![](https://img.aspxhome.com/file/2023/3/68083_0s.jpg)
新手小白学JAVA IDEA下载使用手册全集
2023-11-23 14:33:23
![](https://img.aspxhome.com/file/2023/3/59773_0s.jpg)
解读maven配置阿里云镜像问题
2023-02-28 11:57:56
java实现日期拆分的方法
2023-06-19 00:28:59
java比较器comparator使用示例分享
2022-07-18 22:45:15
VScode 打造完美java开发环境最新教程
2023-02-24 16:02:10
java通过PDF模板填写PDF表单
2022-05-28 16:37:48
![](https://img.aspxhome.com/file/2023/1/66651_0s.jpg)
Java 通过反射给实体类赋值操作
2023-11-26 10:11:41
SpringMVC 数据校验方法(必看篇)
2023-11-14 21:44:05
Java数据结构与算法之循环队列的实现
2023-11-02 11:51:29
![](https://img.aspxhome.com/file/2023/3/58873_0s.gif)
Spring如何使用@Indexed加快启动速度
2022-05-02 10:50:40
![](https://img.aspxhome.com/file/2023/6/62236_0s.jpg)