paulwong

spring3MVC+JSON

 <!-- 自动解析action返回值 解析成json格式 -->
<context:component-scan base-package="com.bplow.*.web" />  
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
    
<property name="messageConverters">  
        
<util:list id="beanList">  
            
<ref bean="mappingJacksonHttpMessageConverter"/>  
        
</util:list>  
    
</property>  
</bean>  
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
    
<property name="supportedMediaTypes">  
        
<list>  
            
<value>text/html;charset=UTF-8</value>  
        
</list>  
    
</property>  
</bean>  
<!-- 自动解析action返回值 解析成json格式 -->

然后需要额外的jar包 jackson 1.1,这里让我很无语,我首先下的1.9放上去什么方法找不到,换1.8x 方法找不到 我一直试到1.6 后来怒了用最老的 好了。。。坑,这绝对是坑啊

然后你的action中直接返回对象,集合,map吧 非常爽啊。测试如下





package com.bplow.test.web;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestAction {

// ResponseBody 对应string则对应ajax getText
@RequestMapping(value = "/testAction", method = RequestMethod.GET)
@ResponseBody
public String allOnActivities() throws UnsupportedEncodingException {

return "{'title':'HelloWorldGOGOGO'}";
}


@RequestMapping(value
= "/testAction2", method = RequestMethod.GET)
@ResponseBody
public TestVo getJsonVo() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
return vo;
}


@RequestMapping(value
= "/testAction3", method = RequestMethod.GET)
@ResponseBody
public List getJsonList() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
List l
= new LinkedList();
l.add(vo);
l.add(vo);
l.add(vo);
l.add(vo);
l.add(vo);
return l;
}


@RequestMapping(value
= "/testAction4", method = RequestMethod.GET)
@ResponseBody
public Map getMap() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
HashMap hsm
= new HashMap();
hsm.put(
"a", 123);
hsm.put(
"b", "123");
hsm.put(
"c", vo);
return hsm;
}

}

posted on 2012-05-18 00:14 paulwong 阅读(1338) 评论(0)  编辑  收藏 所属分类: SPRING MVC


只有注册用户登录后才能发表评论。


网站导航: