1.引入jar包:
在引入基础的Spring和日志logging包外,这里额外引入另外两个包:jackson-core-asl-1.9.13.jar和jackson-mapper-asl-1.9.13.jar;
2.配置Spring配置文件:
在Hello world示例的基础上,加上下面这段配置:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
3.与Hello world示例一样配置web.xml文件
4.编写控制器:
package com.pk.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
public class TestJson {
@RequestMapping("/json")
@ResponseBody
public Map<String, Object> getUsers(){
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("key", "value");
resultMap.put("haha", "123");
return resultMap;
}
}
启动tomcat服务器后,在url栏输入localhost:8080/SpringDemo/json.htm,页面会打印出json字符串:
{"haha":"123","key":"value"}