响应json数据,使用@ResponseBody注解即可。

maven加入jar包:

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.8.2</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.2</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.8.2</version>
</dependency>

springmvc.xml加上配置:

<!-- 配置json -->
<bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	<property name="messageConverters">
		<list>
			<ref bean="mappingJacksonHttpMessageConverter" />
		</list>
	</property>
</bean>
<!-- 配置响应类型 -->
<bean id="mappingJacksonHttpMessageConverter"
	class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
	<property name="supportedMediaTypes">
		<list>
			<value>application/json;charset=UTF-8</value>
		</list>
	</property>
</bean>

控制器:

package com.shuoeasy.springmvc;


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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@RequestMapping("/home")
@Controller
public class Home {
	
	@RequestMapping("/show")
	public String showPage(){
		return "home_index";
	}
	
	@ResponseBody // @ResponseBody表示返回json数据
	@RequestMapping("/show1")
	public User showPage1(){
		User user = new User();
		user.setUid(123);
		user.setUname("张三");
		return user;
	}
	
	@ResponseBody
	@RequestMapping("/show2")
	public Map<Integer,User> showPage2(){
		Map<Integer,User> map = new HashMap<Integer,User>();
		User user1 = new User();
		user1.setUid(123);
		user1.setUname("张三");
		map.put(user1.getUid(), user1);	
		
		User user2 = new User();
		user2.setUid(456);
		user2.setUname("李四");
		map.put(user2.getUid(), user2);
		
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/show3")
	public List<User> showPage3(){
		List<User> list = new ArrayList<User>();
		User user1 = new User();
		user1.setUid(123);
		user1.setUname("张三");
		list.add(user1);	
		
		User user2 = new User();
		user2.setUid(456);
		user2.setUname("李四");
		list.add(user2);
		
		return list;
	}
}


你可能感兴趣的文章