0以后版本返回json格式数据问题,整合的案例

来源:http://www.smjxgs.com 作者:王中王鉄算盘 人气:59 发布时间:2019-08-16
摘要:SpringMVC4.0以后版本返回json格式数据问题,springmvc4.0json 第一次写博文写的不好,但希望能帮助大家,有什么偏颇的地方希望大家多多斧正。在这个问题上困扰了我两天,这两天翻来覆去

SpringMVC4.0以后版本返回json格式数据问题,springmvc4.0json

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

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

4887王中王鉄算盘奖结果 1

4887王中王鉄算盘奖结果 2

2.配置web.xml如下:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns=""
    xmlns:xsi=""
    xsi:schemaLocation="
    ;
    
    <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=""
    xmlns:xsi=""
    xmlns:context=""
    xmlns:mvc=""
    xsi:schemaLocation="
       
        ;   
      <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.结果演示

4887王中王鉄算盘奖结果 3

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

4887王中王鉄算盘奖结果 4

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi=""
    xmlns:context=""
    xmlns:mvc=""
    xsi:schemaLocation="
       
        ;   
      <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>

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

 

第一次写博文写的不好,但希望能帮助大家,有什么偏颇的地方希望大家多多斧正。...

SpringMVC 3.1.2的配置
 
ssi的框架
 
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""
                 xmlns:xsi=""
                 xsi:schemaLocation="
            "
                 version="2.5">

1 导入Jar包

        <servlet>
                <servlet-name>SpringMVC</servlet-name>
                <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>/WEB-INF/classes/spring-*.xml</param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
                <servlet-name>SpringMVC</servlet-name>
                <url-pattern>*.do</url-pattern>
        </servlet-mapping>
</web-app>
 
spring-core.xml
<?xml version="1.0" encoding="UTF-8"?>

2 web.xml

<beans default-autowire="byName"
             xmlns=""
             xmlns:xsi=""
             xmlns:aop=""
             xmlns:context=""
             xmlns:tx=""
             xsi:schemaLocation="
                       
                       
                       
                       
                       
                       
                       
                        ;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
xmlns=""
xsi:schemaLocation=" "
id="WebApp_ID" version="2.5">
<display-name>teacher</display-name>

        <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                <property name="locations">
                        <list>
                                <value>classpath:jdbc.properties</value>
                        </list>
                </property>
        </bean>

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
                <property name="driverClassName">
                        <value>${jdbc.driver}</value>
                </property>
                <property name="url">
                        <value>${jdbc.url}</value>
                </property>
                <property name="username">
                        <value>${jdbc.user}</value>
                </property>
                <property name="password">
                        <value>${jdbc.password}</value>
                </property>
        </bean>

<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>

        <bean id="transactionManager"
                    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSource"/>
        </bean>

<!-- spring MVC配置 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

        <bean id="sqlMapClient"
                    class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
                <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
                <property name="dataSource" ref="dataSource"/>
        </bean>
        <bean id="mysqlDialect" class="com.lavasoft.freamwork.core.dialect.MySQLPhysicalSegmentDialect"/>
        <bean id="sqlExecutor" class="com.lavasoft.freamwork.core.PhysicalSegmentSqlExecutor">
                <property name="dialect" ref="mysqlDialect"/>
        </bean>

<!-- contextConfigLocation配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
    /WEB-INF/applicationContext-bean.xml,
    /WEB-INF/applicationContext-trans.xml,
    /WEB-INF/applicationContext-hibernateTemplate.xml
   </param-value>
</context-param>

        <bean id="baseDao" abstract="true" class="com.lavasoft.freamwork.core.dao.BaseIBatisDAO" init-method="initialize">
                <property name="dataSource">
                        <ref bean="dataSource"/>
                </property>
                <property name="sqlMapClient">
                        <ref bean="sqlMapClient"/>
                </property>
                <property name="sqlExecutor">
                        <ref bean="sqlExecutor"/>
                </property>
        </bean>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 

        <bean id="bk_kindDAO" class="com.lavasoft.dxbk.dao.Bk_kindDAO" parent="baseDao"/>
        <bean id="bk_taskDAO" class="com.lavasoft.dxbk.dao.Bk_taskDAO" parent="baseDao"/>
        <bean id="bk_task_logDAO" class="com.lavasoft.dxbk.dao.Bk_task_logDAO" parent="baseDao"/>
        <bean id="bookDAO" class="com.lavasoft.dxbk.dao.BookDAO" parent="baseDao"/>
        <bean id="ebookDAO" class="com.lavasoft.dxbk.dao.EbookDAO" parent="baseDao"/>
        <bean id="shopdataDAO" class="com.lavasoft.dxbk.dao.ShopdataDAO" parent="baseDao"/>
        <bean id="urlregDAO" class="com.lavasoft.dxbk.dao.UrlregDAO" parent="baseDao"/>
        <bean id="sec_bk_taskDAO" class="com.lavasoft.dxbk.dao.Sec_bk_taskDAO" parent="baseDao"/>
        <bean id="sec_kwDAO" class="com.lavasoft.dxbk.dao.Sec_kwDAO" parent="baseDao"/>
        <bean id="sec_subDAO" class="com.lavasoft.dxbk.dao.Sec_subDAO" parent="baseDao"/>
        <bean id="secbookDAO" class="com.lavasoft.dxbk.dao.SecbookDAO" parent="baseDao"/>
        <bean id="listfileDAO" class="com.lavasoft.dxbk.dao.ListfileDAO" parent="baseDao"/>
        <bean id="str2010DAO" class="com.lavasoft.dxbk.dao.Str2010DAO" parent="baseDao"/>
        <bean id="pdfdirDAO" class="com.lavasoft.dxbk.dao.PdfdirDAO" parent="baseDao"/>

</web-app>

        <bean id="bookSV" class="com.lavasoft.dxbk.service.BookSVImpl">
                <property name="bk_kindDAO" ref="bk_kindDAO"/>
                <property name="bookDAO" ref="bookDAO"/>
        </bean>
</beans>
 
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
4887王中王鉄算盘奖结果,             xmlns:mvc=""
             xmlns:xsi=""
             xmlns:context=""
             xsi:schemaLocation="
               
               
               
               
               
                ;

3 按照web.xml的配置,分别配置spring-servlet.xml, /WEB-INF/applicationContext-bean.xml,
     /WEB-INF/applicationContext-trans.xml,
     /WEB-INF/applicationContext-hibernateTemplate.xml

        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
                <property name="messageConverters">
                        <list>
                                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
                                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                                        <property name="supportedMediaTypes">
                                                <list>
                                                        <value>text/html; charset=utf-8</value>
                                                </list>
                                        </property>
                                </bean>
                                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
                                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
                                <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
                                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
                        </list>
                </property>
        </bean>

spring-servlet.xml:

        <mvc:annotation-driven/>
        <context:component-scan base-package="com.lavasoft.dxbk.web.controller"></context:component-scan>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:mvc=""
xmlns:aop="" xmlns:context=""
xmlns:tx=""
xsi:schemaLocation="
       
       
       
         
         
   
          "
        >
         
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:annotation-config />
<context:component-scan base-package="*">
   
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository" />

        <mvc:resources mapping="/js/**" location="/js/"/>
        <mvc:resources mapping="/css/**" location="/css/"/>

</context:component-scan>

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                <property name="prefix" value="/jsp/"/>
                <property name="suffix" value=".jsp"/>
        </bean>

<mvc:annotation-driven />

</beans>  

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

</beans>  

applicationContext-bean.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:mvc=""
xmlns:aop="" xmlns:context=""
xmlns:tx=""
xsi:schemaLocation="
       
       
       
         
         
   
           
        ">

<aop:aspectj-autoproxy proxy-target-class="true" />
<context:annotation-config />
<context:component-scan base-package="*">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<mvc:annotation-driven />

</beans>

applicationContext-hibernateTemplate.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""  
        xmlns:xsi=""  
        xmlns:context=""  
        xmlns:mvc=""  
        xmlns:cache=""
         xmlns:tx=""
        xsi:schemaLocation="  
           
           
           
           
               
         
         
   
          ">     

<bean id="dataSourceC3p_zh" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="jdbcUrl">
<value>jdbc:mysql://localhost:3306/teacher?characterEncoding=utf-8</value>
</property>
<property name="user">
<value>root</value>
</property>
<property name="password">
<value>0000</value>
</property>
<property name="initialPoolSize" value="3" />
<property name="maxPoolSize" value="10" />
<property name="minPoolSize" value="2" />
<property name="acquireIncrement" value="3" />
<property name="maxIdleTime" value="600" />
<property name="maxStatements" value="0" />
<property name="maxStatementsPerConnection" value="80" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSourceC3p_zh" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.generate_statistics">true</prop> 
</props>
</property>

<property name="mappingResources">
<list>
<value>com/cptl/user/model/teacher.hbm.xml</value>

</list>
</property>

</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>

<!-- 配置事务管理器bean,使用HibernateTransactionManager事务管理器 -->
<!-- 
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
   class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory_zh"/>
</bean>
-->
</beans>

本文由4887王中王鉄算盘奖结果发布于王中王鉄算盘,转载请注明出处:0以后版本返回json格式数据问题,整合的案例

关键词:

上一篇:7集群部署完整版

下一篇:没有了

最火资讯