SpringMVC+ajax返回JSON串

jopen 10年前發布 | 229K 次閱讀 SpringMVC Spring MVC Web框架

一、引言

本文使用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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!