FreeMarker与Spring MVC的结合应用
Freemarker是一种基于java的模板引擎。SpringMVC对FreeMarker进行一些配置的支持,能够利用Freemarker只关注表现层以及Spring MVC的三层分离的特点,向前端输出HTML代码,实现代码和页面完全的隔离。
在SpringMVC中使用FreeMarker需要在spring的配置文件中做配置,首先是在web.xml中配置SpringMVC的Servlet,如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>freemarker_springmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
然后在spring的配置文件applicationContext.xml中加入FreeMarker的配置:
<!-- freemarker配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/templates" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
</props>
</property>
</bean>
其中templateLoaderPath是指定模板文件的位置,freemarkerSetting是对FreeMarker的配置,包括boolean和date时间的显示格式,比如可以设置date_format属性的值为yyyy-MM-ss,格式化格式采用SimpleDateFormat。更多的配置可以参考Configuration和Configurable的API。
最后一步是配置FreeMarker在SpringMVC里面的视图解析器,在freemarker-servlet.xml的文件中添加:
<!-- 针对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 name="requestContextAttribute" value="request" /><!-- 定义request对象名称 -->
<property name="exposeSessionAttributes" value="true" /> <!-- 暴露session属性 -->
</bean>
其中requestContextAttribute属性通过查看springmvc的mvc模板的源码得知,在FreeMarkerViewResolver的父类UrlBasedViewResolver中定义的:
/**
* Set the name of the RequestContext attribute for all views.
* @param requestContextAttribute name of the RequestContext attribute
* @see AbstractView#setRequestContextAttribute
*/
public void setRequestContextAttribute(String requestContextAttribute) {
this.requestContextAttribute = requestContextAttribute;
}
设置requestContext对象的变量名的,这样每个页面都能取得这个对象了。
exposeSessionAttributes的属性设置源码如下:
/**
* Set whether all HttpSession attributes should be added to the
* model prior to merging with the template. Default is "false".
* @see AbstractTemplateView#setExposeSessionAttributes
*/
public void setExposeSessionAttributes(boolean exposeSessionAttributes) {
this.exposeSessionAttributes = exposeSessionAttributes;
}
更多属性设置可以参考spring的文档,这些属性对于velocity模板引擎也是通用的。
Controller代码如下,其中ModelAndView是org.springframework.web.servlet下的:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @Controller
public class TestController { @RequestMapping("/mv")
public ModelAndView test(){
ModelAndView mv = new ModelAndView();
mv.setViewName("main_f");
mv.addObject("user", "bigbang");
return mv;
}
@RequestMapping("/main_first.html")
public String main_first(Model model){
model.addAttribute("user", "bigbang");
return "main_f";
} @RequestMapping("/main_second.html")
public String main_second(Model model){
model.addAttribute("user", "bigbang");
return "main_s";
} @RequestMapping("/anonymous.html")
public String test2(){
return "main_f";
}
}
此处为体现了FreeMarker的使用,所以写了比较多的模块,在此只贴出文件位置图,其中main_f.ftl包含top.ftl、left.ftl和center.ftl,main_s.ftl包含top.ftl、customLeft.ftl和center.ftl:

正常访问下的效果图如下:
请求main_first.html:

请求main_second.html的效果图如下:

FreeMarker与Spring MVC的结合应用的更多相关文章
- FreeMarker与Spring MVC 4集合的HelloWorld示例
0.整体的项目结构 1.引入POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- 【FreeMarker】Spring MVC与FreeMarker整合(二)
前一篇介绍了FreeMarker的基本使用,本例介绍Spring MVC与FreeMarker整合 不熟悉项目搭建,可参考 [FreeMarker]FreeMarker快速入门(一) 整合 1.新建S ...
- FreeMarker与Spring MVC 4结合错误:Caused by: java.lang.NoClassDefFoundError: org/springframework/ui/freemarker/FreeMarkerConfiguration
添加spring-context-support的依赖到POM: <!-- spring-context-support --> <!-- https://mvnrepository ...
- spring mvc+myBatis配置详解
一.spring mvc Spring框架(框架即:编程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依赖注入),AOP(面向切面),MVC(建模M- ...
- Spring MVC+FreeMarker简介
最近做项目,刚接触到SpringMVC与FreeMarker框架,就简单介绍一下自己的理解,不正确的地方请大家指教!! 1.Spring MVC工作原理: 用户发送请求--->前端服务器去找相对 ...
- 【转载】Spring MVC 整合 Freemarker
前言 1.为什么要使用Spring MVC呢? 2.为什么要使用Freemarker呢? 3.为什么不使用Struts2呢? 此示例出现的原因就是发现了struts2的性能太差,所以学习Spring ...
- [Spring MVC] - JSP + Freemarker视图解释器整合
Spring MVC中如果只使用JSP做视图,可以使用下面这段即可解决: <!-- 视图解释类 --> <bean class="org.springframework.w ...
- Spring mvc 中使用ftl引用共通文件出错 FreeMarker template error: Error reading included file "/WEB-INF/ftl/common/errormessage.ftl"
初次接触spring mvc,想做一个小的练习项目,结果在ftl文件中引用其它的共通ftl文件时出错.
- spring mvc + freemarker优雅的实现邮件定时发送
1. spring mvc工程中引入相关freemarker\mail的包 如:pom.xml中加入类似 <dependency> <groupId>javax.mail< ...
随机推荐
- 微信订阅号里实现oauth授权登录,并获取用户信息 (完整篇)
摘要 这段时间一直有人问我,订阅号实现的oauth授权登录的问题,之前写的比较简单,很多人不明白.众所周知,微信公众号分订阅号.服务号.企业号:每个号的用途不一样,接口开放程度也不一样.微信还有个扯淡 ...
- Jmeter组件3. HTTP Cookie Manager
两个坑的地方 如果一个域(scope)内有两个cookie manager,Jmeter说,我分不清了,你自己看着办吧,所以不要没事找事,一个域内一个cookie manager够了 用户自定义coo ...
- C++学习基础七——深复制与浅复制
一.深复制与浅复制基本知识 深复制和浅复制,又称为深拷贝和浅拷贝. 深复制和浅复制的区别如下图1所示: 图1 图1表示的是,定义一个类CDemo,包含int a和char *str两个成员变量, 当深 ...
- ffmpeg - libavutil/attribute.h
在ffmpeg中,这个文件被很多其他的文件所包含.该文件中定义了一些gcc中支持的语言扩展的宏, 例如强制内联,外部内联,pure函数等.并根据是否使用了GCC,以及GCC的版本,把宏转换为 相应的编 ...
- OAuth2集成
目前很多开放平台如新浪微博开放平台都在使用提供开放API接口供开发者使用,随之带来了第三方应用要到开放平台进行授权的问题,OAuth就是干这个的,OAuth2是OAuth协议的下一个版本,相比OAut ...
- sscanf函数和正则表达式
看了几篇介绍sscanf函数,真是发现自己好多东西没理解透,详细介绍使用在sscanf中使用正则表达式. 第一篇: 此文所有的实验都是基于下面的程序: char str[10]; for (int i ...
- js数组合并
// 第一种 var mergeTo = [4,5,6], mergeFrom = [7,8,9]; mergeTo = mergeTo.concat(mergeFrom); mergeTo; // ...
- LC.exe已退出,代码为-1错误
因为证书的原因,把项目中“properties”目录下的“license.licx”文件删除,再编译就成功了.如图:
- jquery 根据年 月设置报表表头
function setTblHeadr(thisTime){ $("#datatable_ajax1 thead").empty(); //获取星期 var weekday=ne ...
- Sql 查找整个数据库中的字符串
--存储过程 CREATE PROCEDURE [dbo].[SP_FindValueInDB] ( @value VARCHAR() ) AS BEGIN SET NOCOUNT ON; DECLA ...