ajax要导什么包,springmvc中使用ajax返回json需要哪些包

匿名用户

1级

2016-07-21 回答

加入对springmvc需要jackson支持包的引入
<dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.6.3</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-core</artifactId>    <version>2.6.3</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-annotations</artifactId>    <version>2.6.3</version></dependency>
不引入支持包,在debug下,spring会抛出异常
配置spring-servlet.xml
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
    <list>
    <ref bean="mappingJackson2HttpMessageConverter" />
    </list>
    </property>
    </bean>
    <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
    <list>
    <value>text/html;charset=UTF-8</value>
    <value>text/json;charset=UTF-8</value>
    <value>application/json;charset=UTF-8</value>
    </list>
    </property>
    </bean>
具体使用方法:
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。 使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。 
ajax json前端请求示例
 jQuery.ajax( {  
    type : 'GET',  
    contentType : 'application/json',  
    url : 'user/list',  
    dataType : 'json',  
    success : function(data) {  
    if (data && data.success == "true") {  
    $('#info').html("共" + data.total + "条数据。<br/>");  
    $.each(data.data, function(i, item) {  
    $('#info').append(  
    "编号:" + item.id + ",姓名:" + item.username  
    + ",年龄:" + item.age);  
    });  
    }  
    },  
    error : function() {  
    alert("error")  
    }  
    });  
后台java controller类
@Controller  
@RequestMapping("/user")  
public class DemoController {  
  @RequestMapping(value = "/list", method = RequestMethod.GET)  
  @ResponseBody  
  public Map<String, Object> getUserList() {  
    logger.info("列表");  
    List<UserModel> list = new ArrayList<UserModel>();  
    UserModel um = new UserModel();  
    um.setId("1");  
    um.setUsername("sss");  
    um.setAge(222);  
    list.add(um);  
    Map<String, Object> modelMap = new HashMap<String, Object>(3);  
    modelMap.put("total", "1");  
    modelMap.put("data", list);  
    modelMap.put("success", "true");  
    return modelMap;  
  }  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值