要理解这篇文章,先理解Spring的@ResponseBody注解 Spring MVC 接收请求参数的注解和响应注解
这是重新整理的,原文 jQuery AJAX 方法 success()后台传来的4种数据
1. 后台返回一个基本类型String,Long等
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Integer addStudent() {
return 67;
}
}
public class Student {
private String name;
private Integer age;
}
2. 后台返回一个实体类
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mx.entity.Student;
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Student addStudent() {
Student student = new Student();
student.setName("mc");
student.setAge(45);
return student;
}
}
3.后台返回一个实体类的集合
package com.mx.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mx.entity.Student;
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public List addStudent() {
List students = new ArrayList();
Student student1 = new Student("mc", 45);
Student student2 = new Student("mz", 22);
students.add(student1);
students.add(student2);
return students;
}
}
4.后台返回一个实体类list(实体类的字段包括List类型)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mx.entity.Student;
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public List addStudent() {
List students = new ArrayList();
Student student1 = new Student("mc", 45,new ArrayList(Arrays.asList(67, 60)));
Student student2 = new Student("mz", 22,new ArrayList(Arrays.asList(90, 80)));
students.add(student1);
students.add(student2);
return students;
}
}