Spring MVC 整合 Freemarker (一)

2014-11-24 09:56:17 · 作者: · 浏览: 3

前言

1.为什么要使用Spring MVC呢

2.为什么要使用Freemarker呢

3.为什么不使用Struts2呢

此示例出现的原因就是发现了struts2的性能太差,所以学习Spring MVC。又由于前一个项目使用的是Struts2+Freemarker写的,所以要替换Struts2就需要让Spring MVC也要支持Freemarker。

项目准备

1.Spring 包

spring2.5.6.jar


spring-aop.jar


spring-beans.jar


spring-context.jar


spring-context-support.jar


spring-core.jar


spring-jdbc.jar


spring-jms.jar


spring-orm.jar


spring-test.jar


spring-tx.jar


spring-web.jar


spring-webmvc.jar


spring-webmvc-portlet.jar


spring-webmvc-struts.jar


2.Freemarker包

freemarker-2.3.19.jar

加粗的部分为项目需要引入的包。

开始我们的整合之旅吧!

开发工具:NetBeans IDE 7.3.1

一、新建web项目springMVCAndFreemarker

二、将jar包引入项目

spring.jar


spring-webmvc.jar


freemarker.jar

依赖包

commons-logging.jar


三、配置web.xml


WEB-INF/web.xml


[html]
!-- Spring 上下文参数 -->

contextConfigLocation
classpath:applicationContext.xml




org.springframework.web.context.ContextLoaderListener


springmvc
org.springframework.web.servlet.DispatcherServlet
1



springmvc
/*



contextConfigLocation
classpath:applicationContext.xml




org.springframework.web.context.ContextLoaderListener


springmvc
org.springframework.web.servlet.DispatcherServlet
1



springmvc
/*
四、添加applicationContext.xml文件

src/applicationContext.xml


[html]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


接着在内容中添加Freemarker的支持配置


[html]

class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">



0
UTF-8
0.##########
yyyy-MM-dd HH:mm:ss
true
ignore



class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">



0
UTF-8
0.##########
yyyy-MM-dd HH:mm:ss
true
ignore



五、添加spring MVC的servlet配置文件,命名规则(servlet-name+servlet.xml)
WEB-INF/springmvc-servlet.xml


[html]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

接着在内容中添加Spring MVC的配置


[html]

class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">

.ftl



class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">

.ftl


六、创建控制器Controller类

co