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

【转载请注明出处:http://blog.csdn.net/leytton/article/details/38535837

SpringMVC系列文章索引 http://blog.csdn.net/leytton/article/details/38502665

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;
	}
}

四、 效果图

SpringMVC学习笔记(7) 返回Json格式数据_第1张图片

你可能感兴趣的:(spring,spring,json,mvc,mvc,springMVC)