一. 前段目录结构如下架构如下:
二. freemarker文件配置
在 web.xml 文件中指定 spring 配置文件的位置
三. 配置springmvc-servlet.xml文件
1)配置自动扫描包 -- 能读取到@Controller相关java包;
2)默认的注解映射的支持 -- 读取静态文件;
3)设置freemarker 的配置文件;
4)设置对静态资源文件的访问;
<?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"> <!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.ajs"></context:component-scan>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven /> <!-- freemarker 的配置文件 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views"/>
</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"/>
</bean> <!-- 对静态资源文件的访问(cache-period的作用暂时不知道) -->
<mvc:resources mapping="/images/**" location="/META-INF/resources/images/" cache-period="31556926" />
<mvc:resources mapping="/js/**" location="/META-INF/resources/js/" cache-period="31556926" />
<mvc:resources mapping="/css/**" location="/META-INF/resources/css/" cache-period="31556926" /> </beans>
上述配置完成之后,在项目中可以访问到对应目录下的静态资源(css/js/images/ftl等)
四. 配置spring.ftl对于读取静态资源
在webmvc对应的目录下copy出对应的spring.ftl文件,放在我们自己的项目中(也可以不copy设置好对应路径直接使用),如下所示:
五. 在 ftl文件中使用静态资源,如下给出示例文件
<#import "../spring.ftl" as spring/> <!-- 找到spring.ftl的相对路径-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>success</title> <link rel="stylesheet" type="text/css" href="<@spring.url '/css/default.css'/>"/>
<script type="text/javascript" src="<@spring.url '/js/jquery-1.12.3.min.js'/>"></script>
</head> <body class="bg">
<h4> success page</h4>
<a href="../index">Index</a>
<img src = "<@spring.url '/images/pig.png'/>"/>
<button id="chgBg">chgBg</button>
</body> <script type="text/javascript">
$(document).ready(function(){
$("#chgBg").click(function(){
$('body').css("background-color","yellow");
});
});
</script>
</html>
此时 freemarker & 静态资源整合即完成;