第一种使用阿里云的fastjson的jar包
下载jar包,地址http://www.pc6.com/softview/SoftView_441783.html
选择普通下载
在spring-mvc文件里加上
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value> text/html; charset=UTF-8</value>
<value> application/json; charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
第二种直接导入三个jar包,无需任何配置
返回json要添加段代码,不然会出现返回json数据时显示的是下载json文件
<!-- 在实际开发中通常都需配置 mvc:annotation-driven 标签 -->
<mvc:annotation-driven>
<!-- 返回json要添加段代码,不然会出现返回json数据时显示的是下载json文件 -->
<mvc:message-converters>
<bean id = "mappingJacksonHttpMessageConverter"
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>
java代码
@RequestMapping("/first")
@ResponseBody
public Object getJson(){
Map<String, Object> map=new HashMap<String, Object>();
map.put("fd", "郝鹏");
return map;
}
@RequestMapping("/list")
@ResponseBody
public Map<String,Object> getUserList(){
List<User> list = new ArrayList<User>();
User user1 = new User();
user1.setUserName("Tom");
user1.setPassword("666666");
User user2 = new User();
user1.setUserName("Jon");
user1.setPassword("888888");
list.add(user1);
list.add(user2);
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("work", "test");
modelMap.put("school", "sanming");
modelMap.put("userlist", list);
return modelMap;
}
jsp代码
<a href="first">first</a><br><br>
<a href="list">list</a><br><br>
运行效果图