SpringMVC+ajax返回JSON串

jopen 6年前

一、引言

本文使用springMVC和ajax做的一个小小的demo,实现将JSON对象返回到页面,没有什么技术含量,纯粹是因为最近项目中引入了springMVC框架。


二、入门例子

①. 建立工程,并导入相应spring jar包和解析json的包fastjson。

②. 在web.xml文件中配置Spring的核心类DispatcherServlet

③. 配置Spring的核心配置文件spring-servlet.xml

④. 编写实体类Person

    public class Person {            private String name;            private Integer age;                    public String getName() {                return name;            }                    public void setName(String name) {                this.name = name;            }                    public Integer getAge() {                return age;            }                    public void setAge(Integer age) {                this.age = age;            }                    public String toString() {                return "[name: " + name + ", age: " + age + "]";            }        }  

⑤. 编写控制器类PersonControll

    @Controller        public class PersonControll {            @RequestMapping("toAjax.do")            public String toAjax() {                return "ajax";            }                        @RequestMapping(value = "ajax.do", method = RequestMethod.GET)            public void ajax(@ModelAttribute Person person,PrintWriter printWriter) {                System.out.println(person);                String jsonString = JSON.toJSONString(person, SerializerFeature.PrettyFormat);                printWriter.write(jsonString);                printWriter.flush();                printWriter.close();            }        }  
⑥. 编写访问页面ajax.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">        <html>            <head>                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">                <title>ajax for springMVC</title>                <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>                <script type="text/javascript">                    $(function() {                        $("#click").click(function() {                            $.ajax( {                                type : "GET",                                url : "ajax.do",                                data : "name=zhangsan&age=20",                                dataType: "text",                                success : function(msg) {                                    alert(msg);                                }                            });                        });                    });                </script>            </head>            <body>                <input id="click" type="button" value="click to show person" />            </body>        </html>  

⑦. 访问url: http://localhost:8080/springMVC/toAjax.do

来自:http://blog.csdn.net/zdp072/article/details/18187033