我决定给一个比较简单 而又实用的配置:
1.依赖的JAR包 如图 SPRING MVC 我的是3.1的
2.
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
p:viewName="index" />
3. RenderJsonView
package sys;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
/**
* 自定义的JsonView,返回json数据
*
* @author wubei
*
*/
@SuppressWarnings("unchecked")
public class RenderJsonView extends MappingJacksonJsonView {
protected void renderMergedOutputModel(Map
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map, ?> result = (Map, ?>) super.filterModel(model);
Object obj = null;
if (result.values().iterator().hasNext()) {
obj = result.values().iterator().next();
}
JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object arg0, String arg1, Object arg2) {
if (arg2 instanceof Set) {
return true;
}
return false;
}
});
if (obj instanceof List) {
response.getWriter().println(JSONArray.fromObject(obj, config));
} else {
response.getWriter().println(JSONObject.fromObject(obj, config));
}
}
}
4.test
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author Administrator
*/
@Controller
public class Test {
@RequestMapping(value="/test.htm")
public ModelAndView test(){
Map
map.put("name","fengxiang");
map.put("age",23);
return new ModelAndView("jsonView").addObject(map);
}
}
ok 了