您的位置:首页 > 编程语言 > Java开发

SpringMVC学习笔记(7) 返回Json格式数据

2014-08-13 14:17 363 查看
【转载请注明出处:/article/2381716.html

SpringMVC系列文章索引 /article/2381709.html



spring mvc自带的jackson 可以十分便捷地将任意对象转化为Json格式数据返回

一、 web工程lib中加入jackson所需jar包

jackson-core-asl-1.9.9.jar、jackson-mapper-asl-1.9.9.jar 可在我的网盘分享下载 http://pan.baidu.com/s/1jGEAZ9G

二、 在配置文件springMVC-servlet.xml中加入jackson配置

<!-- json转换器 -->
	<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
		<property name="supportedMediaTypes" value="application/json"></property>
	</bean>


最终效果

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/uploads/**" location="/uploads/" />

<!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.llqqww.controller" />
<mvc:annotation-driven />

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<!-- json转换器 --> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"></property> </bean>
</beans>


三、 在Controller的Action中添加注解"@ResponseBody"

程序自动将返回的任意对象值转化成json格式数据

Controller

package com.llqqww.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/hi")
public class HelloWorldController{
	
	@RequestMapping("/getUserJson")
	@ResponseBody
	public Map<String, Object> getUserJson(){
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", 1);
		map.put("name", "Leytton");
		map.put("university", "DHU");
		return map;
	}
}


四、 效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: