第一次写博文写的不好,但希望能帮助大家,有什么偏颇的地方希望大家多多斧正。在这个问题上困扰了我两天,这两天翻来覆去睡不着。一直在想这个问题。废话不多说下面进入正题。

1.创建创建web项目,加入SpringMVC的jar,我这里演示用spring-framework-4.2.3.RELEASE。jar包如下图所示:

2.配置web.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>

<servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3.配置applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">   
      <context:component-scan base-package="cn.xugang.."></context:component-scan>
      <mvc:annotation-driven content-negotiation-manager="contentNegotiationManagerFactoryBean"/>
      <mvc:default-servlet-handler/>
      <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean" id="contentNegotiationManagerFactoryBean">
              <property name="favorPathExtension" value="false"/>
              <property name="favorParameter" value="false"/>
              <property name="ignoreAcceptHeader" value="false"/>
              <property name="mediaTypes">
                  <map>  
                    <entry key="xml" value="application/xml"/>  
                    <entry key="json" value="application/json"/>  
                    <entry key="xls" value="application/vnd.ms-excel"/>  
                </map>
              </property>
      </bean>
      <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" id="mappingJacksonHttpMessageConverter">
              <property name="supportedMediaTypes">
                  <list>
                      <value>text/html;charset=UTF-8</value>
                  </list>
              </property>
      </bean>
      <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
              <property name="messageConverters">
                  <list>
                      <ref bean="mappingJacksonHttpMessageConverter"/>
                  </list>
              </property>
      </bean>
      
      
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/jsp/"></property>
              <property name="suffix" value=".jsp"></property>
      </bean>
</beans>

4.配置创建controller,使用@Responsebody注解,指定返回内容。

package cn.xugang.cotroller;

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;

import cn.xugang.entity.User;

@Controller
@RequestMapping("/user")
public class UserCotroller {
    @RequestMapping(value="/hello.html",method=RequestMethod.GET )
    public @ResponseBody User hello(){
        User user=new User();
        user.setAge(19);
        user.setName("test");
        return user;
    }
    @RequestMapping(value="/test.html")
    public String test(){
        System.out.println("hello world");
        return "hello";
    }
}
5.发送异步请求。这个由于本人用了Etx.js,就直接用ext.js发送异步请求了。

Ext.onReady(function(){
    Ext.define('User',{
        extend:'Ext.data.Model',
        fields:['name','age'],
    });
    var store=Ext.create('Ext.data.Store',{
        model:'User',
        proxy:{
            type:'ajax',
            url:'/SpringMVC4/user/hello.html',
            reader:{
                type:'json',
                
            }
        }
        
    });
    
    store.load({
        callback:function(records,operation,success){
            if(success){
                var msg=[];
                store.each(function(user){
                    msg.push(user.get('name')+" "+user.get('age'));
                    
                });
                Ext.MessageBox.alert("提示",msg.join("<br>"));
            }
        }
        
        
    });
    var msg=[];
    store.each(function(user){
        msg.push(person.get('name')+" "+user.get('age'));
        
    });
    Ext.MessageBox.alert('提示',msg.join("<br>"));
    
});

6.结果演示

7.总结:最后简单说一下,SpringMVC4.0以上版本用上述这种方式成功返回json,如果是4.0以下,由于json的解析方式不同,这里也是一个坑,在网上收了很多资料,看了说得是云里雾里,完全无法使用,最后经过自己认真总结得出本文所述内容,4.0以下可使用如下jar包。

并于applicationContext.xml中配置如下代码

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">   
      <context:component-scan base-package="cn.xugang.."></context:component-scan>
      <mvc:annotation-driven/>
      <mvc:default-servlet-handler/>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" id="mappingJacksonHttpMessageConverter">
              <property name="supportedMediaTypes">
                  <list>
                      <value>application/json;charset=UTF-8</value>
                  </list>
              </property>
      </bean>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/jsp/"></property>
              <property name="suffix" value=".jsp"></property>
      </bean>
</beans>

最后,希望帖子对大家有用,由于第一次写,很多地方写的不是很好,请大家多多包涵.如大家对上述有疑惑,可以留言。如转载请注明出处。谢谢大家!

SpringMVC4.0以后版本返回json格式数据问题的更多相关文章

  1. springmvc4.0配置ajax请求json格式数据

    1.导入相关jar包:jackson-annotation-2.5.4.jar,jackson-core-2.5.4.jar,jackson-databind-2.5.4.jar. 2.spring- ...

  2. Django 1.8.11 查询数据库返回JSON格式数据

    Django 1.8.11 查询数据库返回JSON格式数据 和前端交互全部使用JSON,如何将数据库查询结果转换成JSON格式 环境 Win10 Python2.7 Django 1.8.11 返回多 ...

  3. Spring MVC 学习笔记11 —— 后端返回json格式数据

    Spring MVC 学习笔记11 -- 后端返回json格式数据 我们常常听说json数据,首先,什么是json数据,总结起来,有以下几点: 1. JSON的全称是"JavaScript ...

  4. 返回json格式数据乱码

    本文为博主原创,未经允许不得转载: 原本返回json格式数据的代码: @ResponseBody @RequestMapping(value = "getListByTime", ...

  5. WebService返回json格式数据供苹果或者安卓程序调用

    1.新建一个WebService. 2. /// <summary> /// DemoToJson 的摘要说明 /// </summary> [WebService(Names ...

  6. 使用jQuery发送POST,Ajax请求返回JSON格式数据

    问题: 使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code" ...

  7. ajax请求后台,返回json格式数据,模板!

    添加一个用户的时候,需要找出公司下所有的部门,和相应部门下的角色,利用ajax请求,实现联动技术.将返回的json格式数据,添加到select标签下. <script type="te ...

  8. springmvc通过ajax异步请求返回json格式数据

    jsp 首先创建index.jsp页面 <script type="text/javascript"> $(function () { $("#usernam ...

  9. 如何让webapi只返回json格式数据

    最近脑子不好用,总记不住事,以前搞过让webapi只返回json格式的数据,今天有人问我又突然想不起了,后来总结一下,备忘一下,大概有下面几种处理方式 1.在WebApiConfig类的Registe ...

随机推荐

  1. IOS 中关于自定义Cell 上的按钮 开关等点击事件的实现方法(代理)

    1.在自定义的Cell .h文件中写出代理,写出代理方法. @protocol selectButtonDelegate <NSObject> -(void)selectModelID:( ...

  2. (原)Ubuntu14中安装GraphicsMagick

    转载请注明出处: http://www.cnblogs.com/darkknightzh/p/5661439.html 参考网址: http://comments.gmane.org/gmane.co ...

  3. 安卓初步:通讯技术介绍&&安卓介绍

    通讯技术: 1G    模拟制式    只能进行语音通话. 2G    GSM, CDMA    收发短信和邮件. 2.5G    GPRS, EDGE    访问wap网络数据.(图片, 壁纸, 文 ...

  4. 看看国外的javascript题目,你能全部做对吗?(分享)

    本文转自@Aaron的博客,拿过来分享一下.原文:看看国外的javascript题目,你能全部做对吗? 题目一: (function(){ return typeof arguments; })(); ...

  5. HTTP之I/O模型图MPM详细解析

    高度模块化:DSO MPM:多路处理模块      prefork-->一个主进程+多个工作进程,每个工作进程处理多个请求      worker-->一个主进程+多个工作进程,每个工作进 ...

  6. C编译环境的搭建-sublime篇

    1.安装sublime text 2.下载MingW: http://sourceforge.net/projects/mingw-w64/?source=typ_redirect 3.sublime ...

  7. JDBC、Hibernate、Java类型对照表

    Hibernate映射类型 java类型 标准SQL类型 integer java.lang.Integer integer long java.lang.Long bigint short java ...

  8. C++----练习--while求和

    1.完成1+2+3+...+99+100 #include<iostream> int main() { std::cout<<"本程序完成1 + 2 + 3 ... ...

  9. BZOJ 2878 迷失游乐园

    http://www.lydsy.com/JudgeOnline/problem.php?id=2878 题意:n个点的图,保证图联通,有n-1或者n条边,求从任意一个点出发,不经过相同点,最终无路可 ...

  10. LeetCode_Jump Game

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...