SPRING MVC返回JSON数据
用到SPRING的 MappingJacksonJsonView 视图,需要jackson.jar包支持,下载地址http://wiki.fasterxml.com/JacksonDownload
一个测试的例子,配置控制器TestJsonController和视图解析器TestViewResolver:
<bean id="viewViewResolver" class="com.ll19.mvc.test.view.resolver.TestViewResolver"> <property name="order" value="1"/> </bean> <bean id="testJsonController" class="com.ll19.mvc.test.control.TestJsonController"> <property name="prefix" value="/json"/> </bean>
具体代码如下:
package com.ll19.mvc.test.control;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.ll19.mvc.test.bean.TestBean;
/** * 测试控制器 * * @author <a href="http://www.LL19.com/">LL19.com</a> */
public class TestJsonController implements Controller {
/** * 前缀 */
private String prefix;
public String getPrefix() {
return prefix; }
public void setPrefix(String prefix) {
this.prefix = prefix; }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
TestBean testBean = new TestBean();
testBean.setDctime("time");
testBean.setDid(1L);
testBean.setDname("jsonView测试");
ModelAndView mav = new ModelAndView("jsonView");
mav.addObject(testBean);
return mav; }
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.ll19.mvc.test.bean.TestBean;
/** * 测试控制器 * * @author <a href="http://www.LL19.com/">LL19.com</a> */
public class TestJsonController implements Controller {
/** * 前缀 */
private String prefix;
public String getPrefix() {
return prefix; }
public void setPrefix(String prefix) {
this.prefix = prefix; }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
TestBean testBean = new TestBean();
testBean.setDctime("time");
testBean.setDid(1L);
testBean.setDname("jsonView测试");
ModelAndView mav = new ModelAndView("jsonView");
mav.addObject(testBean);
return mav; }
}
TestBean为一个测试BEAN,返回ModelAndView后视图解析器TestViewResolver直接返回MappingJacksonJsonView视图即可:
public View resolveViewName(String viewName, Locale locale) throws Exception { if (viewName.equals("jsonView")) { return new MappingJacksonJsonView(); } return null; }
MappingJacksonJsonView视图便会根据你添加的BEAN对象,自动转换为JSON格式,在例如使用AJAX获取数据后,即可直接用JS操作返回的JSON数据。
测试结果:{"testBean":{"did":1,"dname":"jsonView测试","dctime":"time"}}