1、添加JSON数据转换驱动

  1. 1、pom文件添加JSON依赖
  2. <dependency>
  3. <groupId>com.fasterxml.jackson.core</groupId>
  4. <artifactId>jackson-core</artifactId>
  5. <version>2.9.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.fasterxml.jackson.core</groupId>
  9. <artifactId>jackson-databind</artifactId>
  10. <version>2.9.0</version>
  11. </dependency>
  12. 2、全局配置文件添加驱动,使得可以调用JSON数据转化的类
  13. <mvc:annotation-driven/>(http://www.springframework.org/schema/mvc)

2、Cotroller类和响应的HTML

  1. @Controller
  2. class A{
  3. //返回字符串
  4. @ReuqestMapping("/uri")
  5. @ResponseBody//设置为响应体
  6. public String test01(){
  7. return "String";
  8. }
  9. //返回对象
  10. @ReuqestMapping("/uri")
  11. @ResponseBody//设置为响应体
  12. public Student test01(Student stu){
  13. return stu;
  14. }
  15. //List
  16. @ReuqestMapping("/uri")
  17. @ResponseBody//设置为响应体
  18. public List<Student> test01(List<Student> stus){
  19. return stus;
  20. }
  21. }

3、示例

  1. @Controller
  2. public class TestClass {
  3. @RequestMapping(value = "/some.do",method = RequestMethod.POST)
  4. @ResponseBody
  5. public Student test01(Student student){
  6. return student;
  7. }
  8. @RequestMapping(value = "/string.do",method = RequestMethod.POST,produces="application/json;charset=UTF-8")//设置返回内容为String,编码格式
  9. @ResponseBody
  10. public String test03(){
  11. return "student";
  12. }
  13. @RequestMapping(value = "/other.do",method = RequestMethod.POST)
  14. @ResponseBody
  15. public List<Student> test02(){
  16. List<Student> students = new ArrayList<>();
  17. students.add(new Student(34,"name1"));
  18. students.add(new Student(234,"name2"));
  19. return students;
  20. }
  21. }
  1. <meta charset="UTF-8">
  2. <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
  3. <script type="text/javascript">
  4. $(function () {
  5. $("#a").click(function () {
  6. $.ajax({
  7. url:"some.do",
  8. data:{
  9. name:"历史", age:23,
  10. },
  11. type:"post",
  12. dataType:"json",
  13. success: function (rep) {
  14. alert(rep.name+"\t"+rep.age)
  15. }
  16. })
  17. })
  18. $("#b").click(function () {
  19. $.ajax({
  20. url:"string.do",
  21. type:"post",
  22. success: function (rep) {
  23. alert(rep)
  24. }
  25. })
  26. })
  27. $("#c").click(function () {
  28. $.ajax({
  29. url:"other.do",
  30. type:"post",
  31. dataType:"json",
  32. success: function (rep) {
  33. $.each(rep,function (i,res) {
  34. alert(res.name+"\t"+res.age)
  35. })
  36. }
  37. })
  38. })
  39. })
  40. </script>
  41. <button id="a">点击1</button>
  42. <button id="b">点击2</button>
  43. <button id="c">点击3</button>