Quick FreeMarker in Spring 3 Tutorial

  • Post author:
  • Post category:Java

Here’s a quick way to get you started with FreeMarker. You will need Eclipse Indigo and the m2e Maven Plugin for Eclipse. You will also need a basic understanding of Spring 3 MVC, as we will convert the Spring MVC view from JSPs to FreeMarker.

1. Create a new Maven Project using the Eclipse New Wizard. When prompted for the archetype, pick the spring-mvc-jpa-archetype. This will give us a running Spring MVC web application.

Spring MVC web application

2. Enter com.teamextension for the groupId. Enter quickfreemarker for the artifactId. Enter com.teamextension.quickfreemarker for the package. Hit Finish.

So far we have created a basic Spring MVC web application. Next step is to add FreeMarker support.

3. Right click on the quickfreemarker project and go to Maven -> Add Dependency. Enter the pattern freemarker and pick the org.freemarker freemarker.

This adds the FreeMarker library to our Spring MVC application.

4. Go to src/main/webapp/WEB-INF/spring/app/servlet-context.xml and make the following changes.

Remove the org.springframework.web.servlet.view.InternalResourceViewResolver bean and replace it with

<beans:bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
	<beans:property name="templateLoaderPath" value="/WEB-INF/views/"/>
</beans:bean>

<beans:bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
	<beans:property name="cache" value="true"/>
	<beans:property name="prefix" value=""/>
	<beans:property name="suffix" value=".ftl"/>
</beans:bean>

This changes the ViewResolver from using JSPs to FreeMarker.

5. Now we change the JSPs. Go to src/main/webapp//WEB-INF/views. Rename home.jsp to home.ftl, and then remove the 2 JSP directives on the top of home.ftl.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>

6. Edit src/main/resources/log4j.xml. Look for “org.application” and change it to “com.teamextension”. This will enable debug logging for our web application.

7. Run mvn tomcat:run to test your web application. Here we will create an Eclipse run configuration for Maven so we can run tomcat:run from within Eclipse.

8. Go to http://localhost:8080/quickfreemarker to see your web application in action.

9. For development purposes, you might want to disable caching. Change the cache property in the viewResolver bean to false.

	<beans:property name="cache" value="false"/>

Now you have a fully configured Spring 3 MVC + FreeMarker web application. For a more in-depth look at FreeMarker, please read the official FreeMarker Manual and the Spring MVC View page.

This Post Has One Comment

  1. Rj

    Great dudes thanks a lot 🙂

Comments are closed.