• springMVC框架下返回json格式的对象,list,map


    原文地址:http://liuzidong.iteye.com/blog/1069343

    注意这个例子要使用jQuery,但是jquery文件属于静态的资源文件,所以要在springMVC中设置静态资源访问

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>SpringMVCFile</display-name>
        <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>*.js</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>*.css</url-pattern>
        </servlet-mapping>
        <!-- 配置前台分发器 -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 扫描使用springmvc配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-context.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

    springMVC的配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
        <!-- 扫描包裹,我们完全使用注释定义 Bean 并完成 Bean 之间装配: -->
        <context:component-scan base-package="com.fileUpDown" />
        <!-- 解决了@Controller注解的使用前提配置。 -->
        <mvc:annotation-driven />
        <!-- 配置对静态资源的处理 -->
        <!-- mapping是映射路径,location是本地属性就是webcontent下的目录,web-inf可能访问不到 -->
        <mvc:resources mapping="/file/**" location="/fileHome/" />
    
        <!-- 定义view视图解析器 -->
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass"
                value="org.springframework.web.servlet.view.JstlView" />
            <property name="prefix" value="/" />
            <property name="suffix" value=".jsp" />
        </bean>
        <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <bean
                        class="org.springframework.http.converter.StringHttpMessageConverter">
                        <property name="supportedMediaTypes">
                            <list>
                                <value>text/html;charset=UTF-8</value>
                            </list>
                        </property>
                    </bean>
                </list>
            </property>
        </bean>
        <bean id="mappingJacksonHttpMessageConverter"
            class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
        <!-- 设置文件上传的一些属性 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
            p:defaultEncoding="UTF-8" />
    </beans>

    前台的界面

    <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <!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">
        <%-- <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script> --%>  
        <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.11.0.min.js"></script>
        <title>Spring MVC - jQuery 整合教程</title>
    </head>
    <body>
    <h3>Spring MVC - jQuery 整合教程</h3>
    <h4>AJAX version</h4>
    <p>Demo 1 计算并返回值</p>
    <div style="border: 1px solid #ccc;  250px;">
        Add Two Numbers: <br/>
        <input id="inputNumber1" type="text" size="5"> +
        <input id="inputNumber2" type="text" size="9">
        <input type="submit" id="demo1" value="Add" /> <br/>
        Sum: <br>
        <span id="sum">(Result will be shown here)</span>
    </div>
    <hr><br>
    <p>Demo 2 获取一个对象</p>
    <div style="border: 1px solid #ccc;  250px;">
        <select id="userId">        
            <c:forEach var="index" begin="1" end="5" step="1">
                <option value="${index}">${index}</option>
            </c:forEach>
        </select>
        <input type="submit" id="demo2" value="Get" /> <br/>    
        <span id="info">(Result will be shown here)</span>
    </div>
    <hr><br>
    <p>Demo 3 返回List集合对象</p>
    <div style="border: 1px solid #ccc;  250px;"> 
        <input type="submit" id="demo3" value="Get List User" /> <br/>  
        <span id="listInfo">(Result will be shown here)</span>
    </div>
    <hr><br>
    <p>Demo 4 返回Map集合对象</p>
    <div style="border: 1px solid #ccc;  250px;"> 
        <input type="submit" id="demo4" value="Get Map User" /> <br/>   
        <span id="mapInfo">(Result will be shown here)</span>
    </div>
    <hr><br>
    <a href="${pageContext.request.contextPath}/index.jsp">返回</a>
    <hr><br>
    
    <script type="text/javascript"> 
    $(function() {
         $("#demo1").click(function(){
             //当demo1发生点击事件后,对/main/ajax/add.do发送请求,把传递的数据以json的形式传递,
             //请求完成后使用function(data)函数,把结果显示到页面上来
            $.post("${pageContext.request.contextPath}/main/ajax/add.do",
                        {inputNumber1:  $("#inputNumber1").val(),
                         inputNumber2:  $("#inputNumber2").val() 
                        },
    
                        function(data){                                                                             
                            $("#sum").replaceWith('<span id="sum">'+ data + '</span>');                               
                        });
         });
    
          $("#demo2").click(function(){
            var userId = $("#userId").val();
            $.post("${pageContext.request.contextPath}/main/ajax/getUser/"+userId+".do",
                        null,
                        function(data){     
                            var info = "姓名: " + data.name+",年龄: " + data.age + ",地址: " + data.address + ",性别: " + (data.sex == 1 ? "" : "")+",密码: " + data.password;                                                                      
                            $("#info").html(info);                            
                        });
         });
    
          $("#demo3").click(function(){      
            $.post("${pageContext.request.contextPath}/main/ajax/userList.do",
                        null,
                        function(data){ 
                                var info = '';  
                                 $.each(data,function(index,entity) { 
                                   info += "姓名: " + entity.name+",年龄: " + entity.age + ",地址: " + entity.address + ",性别: " + (entity.sex == 1 ? "" : "")+",密码: " + entity.password+"<br>";   
                                 });
                                 $("#listInfo").html(info);                                               
                        });
         });     
    
         $("#demo4").click(function(){   
            $.post("${pageContext.request.contextPath}/main/ajax/userMap.do",
                        null,
                        function(map){  
                             var info = ''; 
                             $.each(map,function(key,values) { 
                                   info += "key="+key+"<br>";
                                   $(values).each(function(){      
                                       info += "姓名: " + this.name+",年龄: " + this.age + ",地址: " + this.address + ",性别: " + (this.sex == 1 ? "" : "")+",密码: " + this.password+"<br>";
                                    });    
    
                             });
                             $("#mapInfo").html(info);                
                        });
         });     
    
    
    
    });
    </script>
    </body>
    </html>

    com.fileUpDown包下的action jqueryJsonAction.Java

    package com.fileUpDown;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.springMVC.javaBean.User;
    
    @Controller
    @RequestMapping("/main/ajax")
    public class jqueryJsonAction {
        /**
         * 根据映射跳转到指定的页面
         */
        @RequestMapping(value = "/add", method = RequestMethod.GET)
        public String getAjaxAddPage() {
            // 跳转到ajax-add-page
            return "ajax-add-page";
        }
    
        /**
         * 提交表单并进行运算.
         */
        @RequestMapping(value = "/add", method = RequestMethod.POST)
        public @ResponseBody Integer add(@RequestParam(value = "inputNumber1", required = true) Integer inputNumber1,
                @RequestParam(value = "inputNumber2", required = true) Integer inputNumber2) {
            // 实现运算
            Integer sum = inputNumber1 + inputNumber2;
            System.out.println("sum: " + sum);
            // @ResponseBody 会自动的将返回值转换成JSON格式
            // 但是你必须添加jackson的jar包!!!
            return sum;
        }
    
        @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.POST)
        /**
         * @ResponseBody注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,
         * 写入到Response对象的body数据区 使用的时候Controller返回的不是界面的时候,是json或者xml
         */
        /**
         * 当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId},
         * 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
         */
        public @ResponseBody User getUser(@PathVariable("userId") String userId) {
            System.out.println("根据ID获取用户对象: " + userId);
            Map<String, User> users = new HashMap<String, User>();
            users.put("1", new User("123456", "李逵", "123", "成都市", "1", 23));
            users.put("2", new User("565676", "张三", "123", "北京市", "2", 53));
            users.put("3", new User("325566", "李四", "123", "河南省", "2", 93));
            users.put("4", new User("989654", "刘邦", "123", "蒙古包", "1", 13));
            users.put("5", new User("234444", "王熙凤", "123", "成都市", "1", 43));
            return users.get(userId);
        }
    
        @RequestMapping(value = "/userList", method = RequestMethod.POST)
        public @ResponseBody List<User> getUsers() {
            List<User> users = new ArrayList<User>();
            users.add(new User("123456", "李逵", "123", "成都市", "1", 23));
            users.add(new User("123457", "李四", "124", "北京市", "2", 53));
            users.add(new User("123458", "李三", "125", "河南市", "0", 73));
            users.add(new User("123459", "李五", "126", "大路市", "3", 93));
            return users;
        }
        @RequestMapping(value="/userMap",method = RequestMethod.POST)
        public @ResponseBody Map<String,User> getMap(){
            Map<String,User> map = new HashMap<String,User>();
            for(int i=0;i<4;i++){
                map.put(""+i, new User("123456", "李逵", "123", "成都市", "1", i+23));
            }
            return map;
        }
    }

    javaBean对象

    package com.springMVC.javaBean;
    
    public class User {
        private String num;
        private String name;
        private String password;
        private String address;
        private String sex;
        private int age;
        public User(String num, String name, String password, String address, String sex, int age) {
            super();
            this.num = num;
            this.name = name;
            this.password = password;
            this.address = address;
            this.sex = sex;
            this.age = age;
        }
        public String getNum() {
            return num;
        }
        public void setNum(String num) {
            this.num = num;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    
    
    }
  • 相关阅读:
    产品开源了(discuz!nt 2.0),顺便将前些时候发的文章做个总结
    一个曾经的"愤青梦"弥衡
    推荐两个web菜单控件(右击和顶部主菜单)
    一本晚看了两年半的书蓝海战略
    Discuz!NT 在线用户功能简介
    我的2007
    ajax.net调用session和cookie
    最新(2010年)搜索引擎优化(SEO)专家工具集合
    Android学习资料大全
    基于.net的aop实现技术
  • 原文地址:https://www.cnblogs.com/antis/p/7025892.html
Copyright © 2020-2023  润新知