從零開始搭建SSM框架整合freemarker加入html(ftl)與JSP雙視圖解析器

最近在做SSM整合freemarker的時候遇到許多的問題,在網絡上搜羅的資料大部分源自複製粘貼,今天終於通過不斷調試,把整體的freemarker視圖解析器融入到了SSM框架中,本篇文章總結一下Springmvc配置freemarker視圖解析器以及jsp與freemarker雙視圖解析器。從零開始,每一步都會貼出代碼,希望能解決您的問題。

首先是我的配置環境:

idea2018+普通web項目+jdk1.8+tomcat8.5

注:這裏可以使用maven項目搭建,這樣會省去很大的一部分麻煩,這裏我爲了演示,故使用普通的項目來搭建。

聲明:因爲文章字數限制,這裏只演示核心的配置與簡單的測試,文章後邊會有推薦其他博主的文章以幫助你更好的解決問題,如遇到其他問題可以在左側側邊欄聯繫我。

 一、創建項目結構

這裏需要說明一下:

本人使用的是普通的web項目,大家可以爲了便捷的開發使用maven項目。

本人創建基本項目後導入文件產生的基本文件結構如下:

下圖中的jar包需要導入,兩個標註箭頭的jar很關鍵,經常就會忘記導入,導致各種報錯。

maven的pom.xml配置:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>xxxx</groupId>
  <artifactId>xxx</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <!-- Spring、MyBatis版本號及log4j日誌管理包版本 -->
  <properties>
                  <spring.version>5.0.1.RELEASE</spring.version>
                  <mybatis.version>3.4.5</mybatis.version>
                  <slf4j.version>1.7.7</slf4j.version>
                  <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
                  <dependency>
                          <groupId>junit</groupId>
                          <artifactId>junit</artifactId>  
            <version>4.11</version>  
            <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->  
            <scope>test</scope>
                  </dependency>

                  <!-- spring核心包 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-oxm</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <!-- mybatis核心包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>${mybatis.version}</version>  
        </dependency>  
        <!-- mybatis/spring包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        <!-- 導入java ee jar 包 -->  
        <dependency>  
            <groupId>javax</groupId>  
            <artifactId>javaee-api</artifactId>  
            <version>7.0</version>  
        </dependency>  
        <!-- 導入Mysql數據庫鏈接jar包 -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.30</version>  
        </dependency>  
        <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->  
        <dependency>  
            <groupId>commons-dbcp</groupId>  
            <artifactId>commons-dbcp</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        <!-- JSTL標籤類 -->  
        <dependency>  
            <groupId>jstl</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
        <!-- 日誌文件管理包 -->  
        <!-- log start -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>${log4j.version}</version>  
        </dependency>  

        <!-- 格式化對象,方便輸出日誌 -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>fastjson</artifactId>  
            <version>1.1.41</version>  
        </dependency>  

        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-api</artifactId>  
            <version>${slf4j.version}</version>  
        </dependency>  

        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-log4j12</artifactId>  
            <version>${slf4j.version}</version>  
        </dependency>  
        <!-- log end -->  
        <!-- 映入JSON -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.13</version>  
        </dependency> 

        <!-- 上傳組件包 -->  
        <dependency>  
            <groupId>commons-fileupload</groupId>  
            <artifactId>commons-fileupload</artifactId>  
            <version>1.3.1</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-io</groupId>  
            <artifactId>commons-io</artifactId>  
            <version>2.4</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-codec</groupId>  
            <artifactId>commons-codec</artifactId>  
            <version>1.9</version>  
        </dependency>  

                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>1.8.10</version>
                </dependency>

                <dependency>
                    <groupId>org.freemarker</groupId>
                    <artifactId>freemarker</artifactId>
                    <version>2.3.23</version>
                </dependency>

                <dependency>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-core</artifactId>
                    <version>2.7.5</version>
                </dependency>

                <dependency>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                    <version>2.7.5</version>
                </dependency>

                <dependency>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-annotations</artifactId>
                    <version>2.7.5</version>
                </dependency>

  </dependencies>

</project>

 

二、核心配置

1、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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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.xsd
    		http://www.springframework.org/schema/aop
    		http://www.springframework.org/schema/aop/spring-aop.xsd
    		http://www.springframework.org/schema/tx
    		http://www.springframework.org/schema/tx/spring-tx.xsd">
    
	<!-- 1.使用placeHodler讀取外部配置(數據庫信息配置文件) --> 
	<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

	<!-- 2.配置數據庫連接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"/>			
		<property name="url" value="${jdbc.url}"/>			
		<property name="username" value="${jdbc.username}"/>			
		<property name="password" value="${jdbc.password}"/>			
	</bean>
   
   
	<!-- 3.創建sessionFactory對象  SqlSessionFactoryBean -->
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	
		<!-- 3.1關聯數據源 -->
		<property name="dataSource" ref="dataSource"/>
		
		<!-- 3.2讀取mybatis相關的配置信息(讀取mybatis.cfg.xml文件) -->
		<property name="configLocation" value="classpath:mybatis.cfg.xml"/>
		
		<!-- 3.3配置別名註解掃描(配置別名的類在什麼包下:@Alias("user")) -->
		<property name="typeAliasesPackage" value="com.cc.entity"/>
		
		<!-- 3.4關聯映射文件, *表示統配符 -->
		<property name="mapperLocations" value="classpath*:com/cc/mapper/*Mapper.xml"/>
	</bean>
	
	
	<!-- 4.配置事務管理器  DataSourceTransactionManager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<!-- 5.tx事務模板 What-->
	<tx:advice id="crudAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 從上往下匹配 When-->
			
			<!-- 查詢不需要事務 -->
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="list*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			
			<!-- 除了上述的開頭的方法外,其他都需要事務支持 -->
			<tx:method name="*" propagation="REQUIRED"/>		
		</tx:attributes>
	</tx:advice>
	
	<!-- 6.AOP相關的配置:切入事務 -->
	<aop:config>
		<!-- 6.1配置切入點 Where -->
		<aop:pointcut expression="execution(* com.cc.service..*.*(..))" id="pointcut"/>
		<!-- 6.2把Where和What、When關聯 -->
		<aop:advisor advice-ref="crudAdvice" pointcut-ref="pointcut"/>
	</aop:config>

	
	<!-- 7.基於註解:配置service -->
	<!-- 註解包掃描 -->
	<context:component-scan base-package="com.cc"/>
	
	
	<!-- mybatis相關的掃描 -->
	<!-- Mapper接口掃描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 告訴spring,mybatis的mapper接口位於哪個包下 -->
		<!-- spring掃描到這些接口後,會自動的幫你創建代理類,同時納入到spring的容器中 -->
		<property name="basePackage" value="com.cc.mapper"/>
	</bean>
	
</beans>

2、數據源配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bw_practice?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

注:本人這裏使用的數據庫連接驅動包版本爲5.1.44,druid數據源包版本爲1.0.15;數據庫連接驅動包若高於等於8的,需要在連接的url後邊加上時區(serverTimezone=Asia/Shanghai)等相關配置,否則會遇到數據庫報錯。

3、日誌文件配置

log4j.rootLogger = ERROR,stdout

#MyBatis logging configuration...
log4j.logger.com.bw=TRACE
# Console output...
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{HH:mm:ss} %5p %c - %m%n

4、springMVC配置(重要)

<?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.xsd
    		http://www.springframework.org/schema/mvc
    		http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 註解包掃描,只負責掃controller即可 -->
    <context:component-scan base-package="com.cc.controller"/>

    <!-- 註解映射驅動:如JSON的轉換,形參數據填充 控制的註解解析,如:requestMaping-->
    <mvc:annotation-driven/>

    <!-- 靜態資源處理 -->
    <mvc:default-servlet-handler/>
    <mvc:resources mapping="/**" location="/"/>

    <mvc:view-controller path="/" view-name="redirect:/list"/>


    <!-- 配置登錄攔截器 -->
    <!-- <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/enter"/>
            <bean class=""/>
        </mvc:interceptor>
    </mvc:interceptors> -->

    <!--網絡資源視圖解析器,配置視圖格式,也可以是html和jsp-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/JSP/"/><!--前綴-->
        <property name="suffix" value=".jsp"/><!--後綴-->
        <property name="order" value="1"/><!--設置加載的時機或優先級,試圖加載首先掃描是否有freemarker模板故爲0(優先從0開始),若沒有就加載jsp,數值越小優先級越高-->
    </bean>


    <!--配置freemarker交給bean工廠,設置配置文件路徑-->
    <bean id="freemarkerConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:freemarker.properties"/>
    </bean>

    <!--設置freemarker的視圖層配置-->
    <bean id="freemarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="freemarkerSettings" ref="freemarkerConfig"/><!--這裏是上面的bean對象,對象中是配置文件中的freemarker配置信息-->
        <property name="templateLoaderPath" value="/WEB-INF/view/Ftl/"/><!--配置模板的加載的目錄-->
        <property name="freemarkerVariables"><!--配置全局變量,根據個人需要配置-->
            <map>
                <entry key="xml_escape" value-ref="fmXmlEscape"/><!--這裏應用的是下面的這個-->
            </map>
        </property>
    </bean>
    <!--配置全局變量-->
    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>



    <!--配置freemarker視圖解析器-->
    <bean id="freemarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <!--配置視圖模板-->
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
        <!--配置視圖格式,也可以是htm-->
        <property name="suffix" value=".ftl"/>
        <!--設置頁面字符集-->
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <!--設置緩存-->
        <property name="cache" value="true"/>
        <!--設置加載時機-->
        <property name="order" value="0"/>
        <!--本人的視圖前後綴設置省略了,上面的設置就能滿足基本需求-->
        <!-- 還有宏的設置等等,需要使用exposeRequestAttribute/exposeSessionAttribute都被設置爲true時,請求和繪畫屬性都會被複制到模板的屬性集中,但是在這之前,需要把exposeSpringMacroHelpers設置爲true,是開始宏組件的使用。之後就可以在頁面上使用freemarker表達式來訪問或顯示了。-->
    </bean>

        <!--文件上傳設置,需要有 "commons-fileupload:commons-fileupload:1.3.1","commons-io:commons-io:2.4"兩個包-->
    <!--    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="UTF-8"/>
            <property name="maxUploadSize" value="20000000"/>
            <property name="maxInMemorySize" value="40960"/>
        </bean>-->

</beans>

我這裏面打滿了註釋,大部分的配置都會有註釋,若還有沒有明白的,歡迎下方留言。

同時我在這裏提供一份比較乾淨整潔的雙解析器模板:

<?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: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 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <!-- 配置掃描的Controller -->
    <context:component-scan base-package="com.cc.controller" />
    <!-- 使用註解 -->
    <mvc:annotation-driven />

    <!-- 靜態資源處理 -->
    <mvc:default-servlet-handler/>
    <mvc:resources mapping="/**" location="/"/>

    <mvc:view-controller path="/" view-name="redirect:/list"/>

    <!--配置Jsp視圖解析器-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/JSP/"/>
        <property name="suffix" value=".jsp"/>
        <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" />
        <property name="order" value="1"/>
    </bean>

    <!-- 配置freeMarker視圖解析器 -->
    <bean id="ftlViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
        <property name="contentType" value="text/html; charset=utf-8"/>
        <property name="cache" value="true" />
        <property name="suffix" value=".ftl" />
        <property name="order" value="0"/>
    </bean>

    <!-- 配置freeMarker的模板路徑 -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/view/Ftl/" />
        <property name="defaultEncoding" value="utf-8" />
        <property name="freemarkerVariables">
            <map>
                <entry key="xml_escape" value-ref="fmXmlEscape" />
            </map>
        </property>
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">3600</prop>
            </props>
        </property>
    </bean>
    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>

</beans>

注:在實際開發中單解析器一般都無法滿足實際需要,所以雙解析器經常是一般配置;若只需要其中一個,就不用提示了吧。

 5、web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 對靜態資源的配置 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>/img/*</url-pattern>
        <url-pattern>/fonts/*</url-pattern>
        <url-pattern>/font/*</url-pattern>
    </servlet-mapping>

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

    <servlet>
        <servlet-name>spMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>charset</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>charset</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext*.xml</param-value>
    </context-param>
</web-app>

 

6、其他配置

關於mybatis的mapper文件(省略)。

config與ehcache的配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0/EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>


    <!-- 開啓二級緩存 -->
    <settings>
        <!-- 開啓延遲加載 -->
        <!-- <setting name="LazyLoadingEnabled" value="true"/> -->
        <!-- 將積極加載改爲消極加載既按需加載 -->
        <!-- <setting name="aggressiveLazyLoading" value="false"/> -->
        <!-- 開啓二級緩存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>


    <!-- 配置別名批量掃描別名 -->
    <typeAliases>
        <package name="cn.ssmsr.po"/>
    </typeAliases>
</configuration>
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>
	
	
	<!-- eternal:是否永久緩存在內存中 -->
	<!-- timeToIdleSeconds:超過多久(秒)沒有活動,踢出緩存 -->
	<!-- timeToLiveSeconds:從對象創建開始,超過多久(秒),踢出緩存 -->
	<!-- overflowToDisk:超過緩存個數,是否存到磁盤 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="3"
        timeToLiveSeconds="3"
        overflowToDisk="true"
	/>

	 <cache name="com.cc.bean.UsersMapper"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="6"
        timeToLiveSeconds="6"
        overflowToDisk="true"
	/>


</ehcache>

mybatis的延遲加載配置也能配置在spring中,但是那樣子做不是很推薦。

 

三、測試

1、創建視圖層與控制層

視圖層結構:

controller:

package com.cc.controller;

import com.cc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService service;

    @RequestMapping("/index")
    public String index(Map<String,Object> map){
        map.put("name","張三");
        return "index";//index.ftl
    }

    @RequestMapping("/list")
    public String list(Map<String,Object> map){
        map.put("name","張三");
        return "list";//list.jsp
    }
}

頁面的話隨便寫一下夠測試使用就可以了。查看是否能夠正確的解析視圖。

總結:

這裏全是乾貨哦:

1、問題總結

①:jar缺失問題:

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

這個是由於jar包的問題導致的,查看是否缺失我在文章開頭部分的jar,第二個原因可能就是jar衝突的問題,更換某些jar版本嘗試,也可以在下方留言。

②:視圖解析404,頁面調試提示:“HTML 文檔的字符編碼未聲明。如果該文件包含 US-ASCII 範圍之外的字符,該文件將在某些瀏覽器配置中呈現爲亂碼。頁面的字符編碼必須在文檔或傳輸協議層聲明。”

在頁面頭部加入以下的聲明:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

③: 不解析ftl或htm,錯誤解析jsp(只用jsp視圖解析)

這個一定是配置時馬虎大意導致的,可以對照前文認真檢查。本人在配置ftl的後綴格式時寫爲了:*.ftl,倒至無法解析ftl,修改爲 .ftl後恢復正常解析。

2、注意事項

1.在視圖解析器中有一個<property name="order" value="orderValue"/>的配置,這個配置表示解析器的優先級別。我們將FreeMarkerViewResolver的級別設爲0,將InternalResourceViewResolver的級別設爲1。這樣,解析器就會優先使用 FreeMarkerViewResolver 進行解析,如果找不到相應的模板,就使用InternalResourceViewResolver進行解析,如果還找不到頁面,就會產生一個404錯誤!
2.InternalResourceViewResolver比較特殊的,只要視圖名傳給他,都不會再交給下一個order,而是直接forward,所以他的order應該最大,否則後面的視圖解析器都不能有機會處理。 

3、相關有價值的文章推薦:

搭建最基本的Spring+Spring MVC+MyBatis+freemarker整合框架https://www.52pojie.cn/thread-691159-1-1.html

freemarker、jsp多視圖解析器Spring配置https://blog.csdn.net/qq_34021712/article/details/71147364

贈送一圖:圖片較大,推薦打開一個新的頁面或下載進行查看

感謝大家的批評與建議,感謝能夠幫助到您。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章