SpringMVC整合Freemaker

首先需要导入相关jar包

其中: spring-context-support 包一定要导入 如果没有导入将出现以下错误

严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer] for bean with name 'freemarkerConfig' defined in file [你的spring配置文件.xml]: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/springframework/ui/freemarker/FreeMarkerConfigurationFactory

Caused by: java.lang.NoClassDefFoundError: org/springframework/ui/freemarker/FreeMarkerConfigurationFactory

添加freemaker需要的jar包有

spring-context-support.jar

freemarker.jar

其他包则在新建SpringMVC项目的时候就加载进来了

完成jar包的添加,下面则需要在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">

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

  <!--  Spring 服务层的配置文件 --> 
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:config/spring*.xml</param-value>
  </context-param>

  <!--  Spring 容器启动监听器 -->  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!--为DispatcherServlet建立映射 --> 
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <distributable/>
</web-app>

完成了web.xml的配置,下面则需要配置我们的 SpringMVC-servlet.xml

DispatcherServlet会根绝web.xml中配置的去找-servlet.xml的文件来加载spring的一些配置信息。我这里就应该取名叫springmvc-servlet.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/tx 
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring   
  http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

        <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射   请求映射-->  
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  

    <property name="messageConverters">   
             <list>   
                 <bean class = "org.springframework.http.converter.StringHttpMessageConverter">   
                    <property name = "supportedMediaTypes">
                          <list>
                              <value>text/html;charset=UTF-8</value>   
                         </list>   
                    </property>   
                 </bean>   
             </list>   
       </property>  
    </bean> 

        <!--对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> 
      <context:component-scan base-package="com.youto.controller"/>

      <mvc:annotation-driven />

      <!-- 静态文件目录 -->
      <mvc:resources location="/assets/" mapping="/assets/**" />
      <mvc:interceptors>
          <mvc:interceptor>
            <mvc:mapping path="/manager/**"/>              
            <bean class="com.youto.util.ManagerInterceptor" />
          </mvc:interceptor>
      </mvc:interceptors>

      <!--以下三种视图配置根据需要任选一种即可 --> 

     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
     <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
     </bean>-->

     <!-- 针对freemarker的视图配置 -->  
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="cache" value="true" />  
        <property name="prefix" value="" />  
        <property name="suffix" value=".ftl" />  
        <property name="contentType" value="text/html;charset=UTF-8"></property>  
        <property name="requestContextAttribute" value="request" />  
        <property name="exposeSpringMacroHelpers" value="true" />  
        <property name="exposeRequestAttributes" value="true" />  
        <property name="exposeSessionAttributes" value="true" />  
    </bean>

    <!-- View resolvers can also be configured with ResourceBundles or XML files.   
        If you need different view resolving based on Locale, you have to use the   
        resource bundle resolver. -->  
    <!-- 这个是针对返回视图还是json值的视图配置   来分别处理同步和异步请求 -->  
    <!--<bean  
            class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
            <property name="mediaTypes">  
                <map>  
                    <entry key="html" value="text/html" />  
                    <entry key="json" value="application/json" />  
                </map>  
            </property>  
            <property name="favorParameter" value="true" />  
            <property name="viewResolvers">  
                <list>  
                    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />  
                    <bean id="viewResolver"  
                        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
                        <property name="cache" value="true" />  
                        <property name="prefix" value="" />  
                        <property name="suffix" value=".ftl" />  
                        <property name="contentType" value="text/html;charset=UTF-8"></property>  
                        <property name="requestContextAttribute" value="request" />  
                        <property name="exposeSpringMacroHelpers" value="true" />  
                        <property name="exposeRequestAttributes" value="true" />  
                        <property name="exposeSessionAttributes" value="true" />  
                    </bean>  
                </list>  
            </property>  
            <property name="defaultContentType" value="text/html" />  
        </bean>  
        -->  

</beans>

如果是使用freemarker最为视图模板需要再spring的配置文件applicationContext.xml中加入以下配置 由于本人项目中Spring的配置文件叫 spring.xml 故我需要修改的是spring.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:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd 
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="com.youto"/>

    <!-- 加载配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:config/db.properties</value>
            </list>
        </property>
    </bean>

    <!-- freemaker配置 -->
    <bean id="freemarkerConfig"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="/WEB-INF/views/" />  
        <property name="freemarkerSettings">  
            <props>  
                <prop key="template_update_delay">0</prop>  
                <prop key="default_encoding">UTF-8</prop>  
                <prop key="number_format">0.##########</prop>  
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>  
                <prop key="classic_compatible">true</prop>  
                <prop key="template_exception_handler">ignore</prop>  
            </props>  
        </property>  
    </bean>  


    <!-- 配置数据源 -->
    <bean id="dataSource"  class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl">
            <value><![CDATA[jdbc:mysql://${db.host}:${db.port}/${db.database}?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&rewriteBatchedStatements=true]]></value>
        </property>
        <property name="user"               value="${db.userName}" />
        <property name="password"           value="${db.password}" />
        <property name="maxPoolSize"        value="12" />
        <property name="minPoolSize"        value="0" />
        <property name="maxStatements"      value="100" />
        <property name="initialPoolSize"    value="3" />
        <property name="maxIdleTime"        value="10"/>
        <property name="idleConnectionTestPeriod"   value="10" />
        <property name="testConnectionOnCheckin"    value="true" />
        <property name="testConnectionOnCheckout"   value="false" />
        <property name="preferredTestQuery"         value="SELECT 1 FROM DUAL" />
    </bean>

    <!-- 配置读的 ibatis (从库)-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:config/sqlMapConfig.xml"/>
    </bean>


    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>    

     <!-- 事务控制 (主库)-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

注意

在 spring.xml中配置 freemaker的 templateLoaderPath 目录 在springMVC-servlet.xml中则不需要在配置 仅需要在 spring.xml中配置即可.

如果出现以下错误,即有可能是2个都配置了地址或者是配置的目录错误

Could not resolve view with name ‘free’ in servlet with name ‘springMVC’

以上 我们就完成了freemaker和springMVC的整合.下面是我们的测试 controller

import javax.servlet.http.HttpServletRequest;  

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

@Controller  
public class SpringMvcController {  

    @RequestMapping(value="/welcome",method=RequestMethod.GET)   
    public ModelAndView getFirstPage() {  
                //welcom就是视图的名称(welcome.ftl)  
        ModelAndView mv = new ModelAndView(); 
        mv.setViewName("welcome"); 
        mv.addObject("name", "this is freemaker test!!!");  
        return mv;  
    }  
}

welcome.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>Insert title here</title>  
</head>  
<body>  
Hello ${name}  
</body>  
</html>

运行我们的项目:输入 htp://localhost:8080/你的项目名/welcome controller的地址在配置文件中配置过滤器

页面就会显示

Hello this is freemaker test!!!

工程Demo下载地址

本文作为初学者的学习的记录,以便之后查阅。谢谢。

谢谢您的阅读,希望本站及文档能带给你帮助,给你带来简洁明了的阅读体验。谢谢。

本文地址:http://www.laileshuo.com/?p=867

博客地址:www.laileshuo.com www.laileshuo.cn

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值