springmvc+ajax+json向controller传送多个bean

这里实在别人的框架里写的东西,有些东西可能没有用到,凡是和这块有关的全部写下来,方便以后使用

首先是ajax

$("#save").click(function () {
       
                var array=[];
                array.push({name:'张三',age:22});
                array.push({name:'李四',age:23});
                $.ajax({
                    url: "请求路径",
                    type: "POST",
                    contentType: 'application/json;charset=utf-8', //设置请求头信息
                    data: $.toJSON(array),    //将Json对象序列化成Json字符串,需要引入jquery.json.js
                    success: function () {
                        alert("操作成功");
                    },
                    error: function () {
                        alert("操作失败");
                    }
                });
    });

 controller

/**
     * 
     * @param users这里必须用数组,网上查的都是用的List<User>,用集合的话,传过来的值不是User,而是Map,可能是哪里配置的问题
     */
@ResponseBody
    @RequestMapping(value = "与ajax的url保持一致", method = RequestMethod.POST)
    public void update(@RequestBody User[] users) {
        for (User user : users) {
            System.out.println(user);
        }
    }

 还需要导入json的jar包,这里用的是jackson,总共导入2jar包,jackson-core-asl,jackson-mapper-asl

然后配置文件springmvc.xml

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="ignoreAcceptHeader" value="true"/>
        <property name="defaultContentType" value="text/html"/>
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/views/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
            </list>
        </property>
    </bean>

到这里就可以了

猜你喜欢

转载自liguangqinlong.iteye.com/blog/2342824