SpringMVC返回json数据

gradle配置:

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.7'

SpringMVC配置文件中需要添加如下配置:

<mvc:annotation-driven/>

<mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学者快速应用默认配置方案。<mvc:annotation-driven /> 会自动注册RequestMappingHandlerMapping 以及 RequestMappingHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
后面,我们处理响应ajax请求时,就使用到了对json的支持。

<context:annotation-config> 
declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.
<mvc:annotation-driven /> 
is actually rather pointless. It declares explicit support for annotation-driven MVC controllers (i.e.@RequestMapping, @Controller, etc), even though support for those is the default behaviour.
My advice is to always declare <context:annotation-config>, but don't bother with <mvc:annotation-driven /> unless you want JSON support via Jackson.



测试:

package com.xiya.springmvc.handlers;

import com.xiya.springmvc.entities.Address;
import com.xiya.springmvc.entities.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by N3verL4nd on 2017/4/1.
 */
@Controller
public class JsonTest {
    @RequestMapping("/ajax2")
    @ResponseBody
    public List<User> ajax2() {
        List<User> list = new ArrayList<>();
        Address address = new Address("shandong", "liaocheng");
        User user = new User("熙雅", "*****", "*****@qq.com", 24, address);
        list.add(user);
        return list;
    }
}

<mvc:annotation-driven/>
 单独如上设置,在IE浏览器访问,会弹出来下载链接。可以如下设置:

<mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

这里需要强调一下,JSON默认的MIME类型为application/json,

<value>text/html;charset=UTF-8</value> 
如果这样设置,你获得到的是JSON字符串,需要使用JSON.parse()或者eval()函数转化为JSON对象。


综上,使用SpringMVC返回json步骤:

1、加入jackson的jar包。

2、编写controller方法,使其返回JSON对应的对象或者集合。

3、在方法上添加@ResponseBody注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N3verL4nd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值