将数据转换成json数据
Controller类
@Controller
public class UserController {
@RequestMapping("/m1")
public String m1(){
System.out.println("进入m1方法....");
return "m1";
}
//同步请求 返回页面和数据
@RequestMapping("/m2")
public ModelAndView m2(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","今天星期一");
mv.setViewName("m1");
return mv;
}
//异步请求 响应一个字符串
@RequestMapping("/m3")
public void m3(HttpServletResponse response) throws IOException {
response.getWriter().println("hello,word");
}
//异步请求 响应一个对象
@RequestMapping("/m4")
public void m4(HttpServletResponse response) throws IOException {
response.getWriter().println("{id:1,name:\"admin\",address:\"武汉\"}");
}
// 通过jackjson将对象转换成json数据
@RequestMapping("/m5")
@ResponseBody//返回学生对象,转json
public Student m5 (){
Student student = new Student();
student.setId(1);
student.setName("admin");
student.setAddress("wuhan");
return student;
}
//将集合转换为json数据
@RequestMapping("/m6")
@ResponseBody//返回学生对象,转json
public List<Student> list (){
List<Student> list = new ArrayList<>();
for(int i=1;i<=3;i++){
Student s = new Student();
s.setId(i);
s.setName("admin"+i);
s.setAddress("wuhan"+i);
}
return list;
}
}
学生类
package com.hehe.controller;
/**
* 学生类 alt+insert 快捷键
*/
public class Studnet {
private Integer id;//学号
private String name;//姓名
private String address;//地址
//toString方法
//get和set方法
}
配置文件
<!--配置json数据转换-->
<mvc:annotation-driven></mvc:annotation-driven>
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.0</version>
</dependency>