SpringMVC返回json的实例代码

  1. 云栖社区>
  2. 博客>
  3. 正文

SpringMVC返回json的实例代码

pandamonica 2017-12-30 20:42:38 浏览1277
展开阅读全文

说实话,参考了很多网上的文章,压根无法调通。
而且SpringMVC的这部分知识,我也基本没有搞懂。
好在他的代码是通的,我们来看看效果:
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="2.4"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>RepositoryCheck HUB</display-name>
  <!-- dao和service层的Spring配置文件 -->
  <!-- access的配置文件是accessContext.xml; mysql的配置文件是mysqlContext.xml -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/mysqlHibernateContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  
      <!-- 作用:Spring管理hibernate的Session,在事务管理的类执行完后,不立刻关闭Session, 而将Session保存在一个线程变量中,在线程退出前关闭Session;这样在整个request过程中 始终使用一个session,也就可以在request的任何时期lazy loading数据。 主要是为了实现hibernate的延迟加载功能 -->
    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>flushMode</param-name>
            <param-value>AUTO</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>
  
  
  <!-- web层的Spring配置文件 -->
      <servlet>
        <servlet-name>ruku</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ruku</servlet-name>
        <url-pattern>/</url-pattern>

    </servlet-mapping>
    
   <!-- 过滤器 编码 防止中文乱码 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    <!-- 默认入口访问文件 -->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

spring核心配置文件(这个文件没有改)

<?xml version="1.0" encoding="UTF-8"?>  
<!-- 集成hibernate之后的Spring的applicationContext配置文件 -->
<!-- mysql dao和service层的Spring配置文件 -->
<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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        classpath:/org/springframework/beans/factory/xml/spring-beans.xsd     
        http://www.springframework.org/schema/context
        classpath:/org/springframework/context/config/spring-context.xsd
        http://www.springframework.org/schema/aop
        classpath:/org/springframework/aop/config/spring-aop.xsd
        http://www.springframework.org/schema/tx
        classpath:/org/springframework/transaction/config/spring-tx.xsd
        http://www.springframework.org/schema/jdbc
        classpath:/org/springframework/jdbc/config/spring-jdbc.xsd
        http://www.springframework.org/schema/mvc  
        classpath:/org/springframework/web/servlet/config/spring-mvc.xsd">  
           
    <context:component-scan base-package="com.tsmi.hibernate.web"/>
    <context:component-scan base-package="com.tsmi.hibernate.service"/>   
    <context:component-scan base-package="com.tsmi.hibernate.dao"/>    
    <context:component-scan base-package="com.tsmi.mysql.dao"/>
    <context:component-scan base-package="com.tsmi.mysql.service"/>
    <!--  context:component-scan base-package="com.tsmi.mysql.web"/-->
    <context:component-scan base-package="com.tsmi.RepositoryCheck.dao"/>
    <context:component-scan base-package="com.tsmi.RepositoryCheck.service"/>
    <!-- context:component-scan base-package="com.tsmi.RepositoryCheck.web"/-->
    
    
    <!--com.mysql.cj.jdbc.Driver-->
    <!--配置文件-->    
    <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="locations">
         <list>
            <value>classpath:/mysqlHibernateContext.properties</value>
         </list>
     </property>
    </bean>
        
    <!-- 配置mysql数据源, 阿里巴巴的druid-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close" 
        p:driverClassName="${jdbc.driver}"
        p:url="${jdbc.url}"
        p:username="${jdbc.username}"
        p:password="${jdbc.password}" 
        p:initialSize="${ds.initialSize}"
        p:minIdle="${ds.minIdle}"
        p:maxActive="${ds.maxActive}"
        p:maxWait="${ds.maxWait}"
        p:timeBetweenEvictionRunsMillis="${ds.timeBetweenEvictionRunsMillis}"
        p:minEvictableIdleTimeMillis="${ds.minEvictableIdleTimeMillis}"
        p:removeAbandoned="${ds.removeAbandoned}"
        p:removeAbandonedTimeout="${ds.removeAbandonedTimeout}"
        p:defaultAutoCommit="true" />
        
    <!-- spring为集成hibernate提供的LocalSessionFactoryBean -->    
    <!-- 指定数据源 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="hibernateProperties">
          <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">true</prop>
          </props>
       </property>
       <property name="packagesToScan" value="com.tsmi.hibernate.entity"/>
    </bean>

    <!-- 配置Hibernate的事务管理器  : 注入SessionFactory 会话工厂 -->
     <bean id="transactionmanager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> 
         <property name="sessionFactory" ref="sessionFactory"/>
    </bean> 
    
   <!--   事务 aop 配置-->
    <aop:config>
        <!--   定义一个切入点-->
        <aop:pointcut id="serviceMethods"
            expression="execution(* com.tsmi..*.service.*Service.*(..))" />
        <!--   对切入点和事务的通知,进行适配-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
    </aop:config>
     
        <!-- 事务管理 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionmanager">
        <tx:attributes>
            <!-- 定义以下开头的方法名都是只读的模式 -->
            <tx:method name="select*" read-only="true" />
            <tx:method name="count*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="load*" read-only="true" />
            <!-- 其他所有方法都使用事务 -->
            <tx:method name="*" propagation="REQUIRED" read-only="false"
                rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    
    <!--  -->
    <tx:annotation-driven transaction-manager="transactionmanager"/>
    <!-- 配置JdbcTemplate -->
    <bean id="jdbcTemplate" 
        class="org.springframework.jdbc.core.JdbcTemplate">
         <property name="dataSource" ref="dataSource"/>
    </bean>    
</beans> 

spring-mvc配置文件

<!--web层spring配置文件  -->
<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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        classpath:/org/springframework/beans/factory/xml/spring-beans.xsd     
        http://www.springframework.org/schema/context
        classpath:/org/springframework/context/config/spring-context.xsd        
        http://www.springframework.org/schema/mvc  
        classpath:/org/springframework/web/servlet/config/spring-mvc.xsd">


       <!-- 装载web层的controller -->
    <context:component-scan base-package="com.tsmi.hibernate.web" />
    
    
    <!-- 支持返回json(避免IE在ajax请求时,返回json出现下载 ) -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="com.tsmi.hibernate.interceptor.FastJsonHttpMessageConverter">
<!--                      <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>  -->
                     <property name="features">
                        <array>
                        <!-- 
                                QuoteFieldNames-输出key时是否使用双引号,默认为true WriteMapNullValue-是否输出值为null的字段,默认为false 
                                WriteNullNumberAsZero-数值字段如果为null,输出为0,而非null WriteNullListAsEmpty-List字段如果为null,输出为[],而非null 
                                WriteNullStringAsEmpty-字符类型字段如果为null,输出为"",而非null WriteNullBooleanAsFalse-Boolean字段如果为null,输出为false,而非null 
                                DisableCircularReferenceDetect 避免默认的循环引用替换 WriteDateUseDateFormat Date的日期转换器
                             -->
                            <value>QuoteFieldNames</value>
                            <value>WriteMapNullValue</value>
                            <value>WriteNullStringAsEmpty</value>
                            <value>WriteNullNumberAsZero</value>
                            <value>DisableCircularReferenceDetect</value>
                            <value>WriteDateUseDateFormat</value>
                        </array>
                    </property> 
                </bean>
            </list>
        </property>

    </bean>


    <!-- 为视图解析器 配置前缀和后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />  
</beans> 

上面三个配置文件

然后下面是controller代码:

    @RequestMapping("/dologin")
    @ResponseBody
    public ResultBean getRecordNewDefault(HttpServletRequest request, User user) {
        
        User us1 = rus.getOneUser(user.getPernr());
        
        ResultBean result = new ResultBean();
        if (us1 == null) {
            System.out.println("用户不存在");
        } else if (!us1.getKeystr().equals(rus.EncodeFunc(user.getKeystr()))) {
            System.out.println("密码不对");
        } else {

            try {
                List<User> rl1 = rus.getUsers();
                result.setData(rl1);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setMessage(e.getMessage());
            }
        }
        
        return result;
    }

_

网友评论

登录后评论
0/500
评论
pandamonica
+ 关注