SpringMvc完成ajax功能

1.加入jackson的jar包

2.在响应的方法上加上@ResponseBody:把java对象转化为json对象

3.方法的返回值可以是对象集合字符串

 1 @Controller
 2 @RequestMapping("ajax")
 3 public class Ajaxcontroller {
 4     @RequestMapping("Ajax1")
 5     @ResponseBody
 6     public String example(String name) {
 7         System.out.println(name);        
 8         return "你好";
 9     }
10     
11     @RequestMapping("Ajax2")
12     @ResponseBody
13     public Users example2(String name) {
14         System.out.println(name);
15         Users user = new Users("张三","man",23);
16         return user;
17     }
18     
19     @RequestMapping("Ajax3")
20     @ResponseBody
21     public List<Users> example3(String name) {
22         System.out.println(name);
23         List<Users> list=new ArrayList<Users>();
24         Users user1 = new Users("张三1","man",23);
25         Users user2 = new Users("张三2","man",23);
26         Users user3 = new Users("张三3","man",23);
27         Users user4 = new Users("张三4","man",23);
28         list.add(user1);
29         list.add(user2);
30         list.add(user3);
31         list.add(user4);
32         return list;
33     }

4.返回字符串时会有乱码,解决办法

第一种:在@RequestMapping后写入(value="Ajax1",produces="text/html;charset=UTF-8")。代码如下:

1 @RequestMapping(value="Ajax1",produces="text/html;charset=UTF-8")
2     @ResponseBody
3     public String example(String name) {
4         System.out.println(name);        
5         return "你好";
6     }

第二种:在springMVC配置文件中通过org.springframework.web.servlet.view.InternalResourceViewResolver类重写代码编码。代码如下:

1     <mvc:annotation-driven>
2         <mvc:message-converters>
3             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
4                 <constructor-arg index="0" value="utf-8"></constructor-arg>
5             </bean>
6         </mvc:message-converters>
7     </mvc:annotation-driven>

 

posted @ 2019-09-03 21:08  猪头太笨  阅读(223)  评论(0编辑  收藏  举报