SpringMVC整合Freemaker

首先須要導入相關jar包html

其中: spring-context-support 包必定要導入 若是沒有導入將出現如下錯誤java

嚴重: 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包有mysql

spring-context-support.jarweb

freemarker.jarspring

其餘包則在新建SpringMVC項目的時候就加載進來了sql


完成jar包的添加,下面則須要在web.xml中添加相關配置json

<?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.xmlspring-mvc

DispatcherServlet會根絕web.xml中配置的<servlet-name>去找<servlet-name>-servlet.xml的文件來加載spring的一些配置信息。我這裏就應該取名叫springmvc-servlet.xml mybatis

<?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.xmlmvc

<?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!!!

相關文章
相關標籤/搜索