spring mvc jsonView 配置

spring mvc 是个灵活的开源框架 深受大家的喜爱,正因为灵活,所以一个简单的返回JSON 数据的功能,有太多五花八门的配置,看得让人目不暇接。
我决定给一个比较简单 而又实用的配置:
1.依赖的JAR包 如图 SPRING MVC 我的是3.1的
2.<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!-- 启动注解驱动的 Spring MVC 功能, 注册请求 url 和注解 POJO 类方法 的映射 -->
<mvc:annotation-driven />
<!-- 启动包扫描功能,以便注册带有 @Controller 、 @Service 、 @repository 、 @Component 等注解的类成为
spring 的 bean ,不在此spring容器中扫描注册  @Controller 、 @Service,因为此时的service还没有事务特性-->
<context:component-scan base-package="com" >
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>
   <!-- JSON视图 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> 
<property name="order" value="1" />
</bean>
    <bean id="jsonView" class="sys.RenderJsonView"></bean>
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
   
    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

</beans>

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<String, Object> model,
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<String,Object> map = new HashMap<String,Object>();
        map.put("name","fengxiang");
        map.put("age",23);
        return new ModelAndView("jsonView").addObject(map);
    }
}

ok 了

猜你喜欢

转载自f303153041.iteye.com/blog/1946562