`
elicer
  • 浏览: 133174 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring MVC and FreeMarker Sample

阅读更多

Today we will create a Spring MVC based application that uses Freemarker FTL as view instead of JSP. This would give you a good insight in Spring MVC + Freemarker integration. The application is similar to previous tutorial’s User app, where a list of users will be displayed and also we can add new user.

The application is very simple:

  1. There is a table that displays user info like firstname, lastname.
  2. New user can be added via Add User form.

Below is the wireframe of our final freemarker based spring mvc 3 app.
freemarker-servlet-wireframe

So lets get started.

Things We Need

Before we starts with our Spring MVC 3 + FreeMarker example, we will need few tools.

  1. JDK 1.6 or above (download)
  2. Tomcat 6.x or above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.4.x or above (download)
  4. Spring MVC 3.1.2 or above (download)
  5. Freemarker JAR v2.3.15 or above(download)

Let us start with our Spring MVC based Freemarker application.

Step 1: Getting Started

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

dynamic web project in eclipse

After selecting Dynamic Web Project, press Next.

eclipse dynamic web project

Write the name of the project. For example Freemarker_SpringMVC_example. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer. This is how the project structure would look like when we finish the tutorial and add all source code.

springmvc-freemarker-ftl-project-structure

Till this step, our basic Eclipse web project is ready. We will now add Spring MVC and Freemarker support to this project.

Step 2: Adding Spring MVC Support

First copy all required Spring MVC and supporting JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists. Don’t worry if you do not have these JARs. You can download the complete source code with JAR files at the end of this tutorial.

Next we change web.xml (deployment descriptor) and add Spring MVC support to it. If you do not know why we do this, I strongly recommends you to go through Spring 3 MVC Tutorial series.

Related: Spring 3 MVC hello world example

Update the web.xml with following code:

File: /WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
         
  <display-name>Freemarker_SpringMVC_example</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

The above code in web.xml will map DispatcherServlet with url pattern *.html. One thing to note here is the name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will look for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. In this example, the framework will look for file called spring-servlet.xml.

Create a new file spring-servlet.xml under /WebContent/WEB-INF/ folder. This is the spring configuration. Copy following code into it.
File: /WebContent/WEB-INF/spring-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <!-- freemarker config -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    </bean>
     
    <!--
      View resolvers can also be configured with ResourceBundles or XML files. If you need
      different view resolving based on Locale, you have to use the resource bundle resolver.
    -->
    <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>
 
    <context:component-scan
        base-package="net.viralpatel" />
          
</beans>

In the above xml configuration file, we have defined a tag <context:component-scan>. This will allow Spring to load all the components from package net.viralpatel and all its child packages. This will load our UserController class. Also we have defined a bean viewResolver. We usesorg.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver as view resolver. Also notice how we defined bean freemarkerConfig. This defines Freemarker configuration, in our case just one property templateLoaderPath; the path where we will store all our .ftl template files.

Thus the bean viewResolver will resolve the freemarker template view. Note that in our UserController class, we have return a view name “index”. This will be resolved to path /WEB-INF/ftl/index.ftl byFreeMarkerViewResolver.

Step 3: Create Spring MVC Controller

File: /src/net/viralpatel/UserController.java

package net.viralpatel;
 
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class UserController {
    /**
     * Static list of users to simulate Database
     */
    private static List<User> userList = new ArrayList<User>();
 
    //Initialize the list with some data for index screen
    static {
        userList.add(new User("Bill", "Gates"));
        userList.add(new User("Steve", "Jobs"));
        userList.add(new User("Larry", "Page"));
        userList.add(new User("Sergey", "Brin"));
        userList.add(new User("Larry", "Ellison"));
    }
 
    /**
     * Saves the static list of users in model and renders it
     * via freemarker template.
     *
     * @param model
     * @return The index view (FTL)
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("model") ModelMap model) {
 
        model.addAttribute("userList", userList);
 
        return "index";
    }
 
    /**
     * Add a new user into static user lists and display the
     * same into FTL via redirect
     *
     * @param user
     * @return Redirect to /index page to display user list
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user) {
 
        if (null != user && null != user.getFirstname()
                && null != user.getLastname() && !user.getFirstname().isEmpty()
                && !user.getLastname().isEmpty()) {
 
            synchronized (userList) {
                userList.add(user);
            }
 
        }
 
        return "redirect:index.html";
    }
 
}

The UserController is a simple Spring 3 MVC controller that handles request/response. We have created a private static List userList which stores the user entries. Note that in ideal example you would like to read data from database. But for sake of simplicity we will stick to static List :)

There are two methods index() and add(), both mapped via @RequestMapping annotation. The index() method will simply store the users list in model object and render “index” view (index.ftl). And the add() method gets the user details from html form and add it inside static List. Once the add() has added user, it simply redirects the request to /index.html which will render the user list.

Apart from the above UserController class, we will also need a bean class User which holds the user information like firstname, lastname etc.

File: /src/net/viralpatel/User.java

package net.viralpatel;
 
public class User {
    private String firstname;
    private String lastname;
 
    public User() {
    }
 
    public User(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
 
    }
 
    //Add Getter and Setter methods
 
}

Now add Freemarker view in your project.

Step 4: Create Freemarker Template Files

Create a new file index.ftl under folder /WebContent/WEB-INF/ftl/. Copy following content into it.

File: /WebContent/WEB-INF/ftl/index.ftl

<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
    <a href="http://viralpatel.net"><img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/></a>
    FreeMarker Spring MVC Hello World
</H2>
</div>
 
<div id="content">
     
  <fieldset>
    <legend>Add User</legend>
  <form name="user" action="add.html" method="post">
    Firstname: <input type="text" name="firstname" /> <br/>
    Lastname: <input type="text" name="lastname" />   <br/>
    <input type="submit" value="   Save   " />
  </form>
  </fieldset>
  <br/>
  <table class="datatable">
    <tr>
        <th>Firstname</th>  <th>Lastname</th>
    </tr>
    <#list model["userList"] as user>
    <tr>
        <td>${user.firstname}</td> <td>${user.lastname}</td>
    </tr>
    </#list>
  </table>
 
</div
</body>
</html

This is a simple FTL template file. We just iterate model["userList"] list in a loop and prints user’s firstname and lastname in table.

That’s All Folks

You may want to run the application see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.

To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)

URL: http://localhost:8080/Freemarker_SpringMVC_example/index.html
freemarker-springmvc-ftl-example

1
6
分享到:

相关推荐

    spring-mvc-test-sample-master.zip_spring mvc_springmvc-test

    10. **Unit Testing and Integration Testing**:在"spring-mvc-test-sample-master"项目中,很可能包含了对这些控制器和业务逻辑的单元测试以及集成测试,使用JUnit、Mockito等工具进行。 11. **Spring MVC Test ...

    my spring mvc sample app

    在这个名为"my spring mvc sample app"的项目中,我们看到的是一个基础的Spring MVC应用实例,它能够成功运行并展示基本的功能。 Spring MVC的核心概念包括控制器(Controller)、模型(Model)、视图(View)和...

    springmvc实战项目sample

    - `src/main/webapp/WEB-INF`:Web应用的配置文件,如web.xml、SpringMVC的配置文件(spring-mvc.xml)等。 - `src/main/webapp/WEB-INF/views`:视图模板文件,如JSP、Thymeleaf或FreeMarker等。 3. **配置文件...

    spring-mvc-sample:Spring MVC 项目的引导程序示例

    Spring MVC 支持多种视图技术,如 JSP、Thymeleaf 或 FreeMarker。 - **Controller**:控制器层作为模型和视图之间的桥梁,处理请求,更新模型,并选择合适的视图进行渲染。 5. **ModelAndView** `ModelAndView` ...

    springMVC sample

    Spring MVC支持多种视图技术,包括JSP、FreeMarker、Thymeleaf等。视图解析器(View Resolver)根据逻辑视图名映射到实际视图。 3. **控制器(Controller)**:控制器接收HTTP请求,处理业务逻辑,然后将结果传递给...

    我的mvc示例代码

    在"aris-mvc-sample"这个压缩包中,应该包含了上述各部分的代码实现,包括Spring MVC的配置文件、Controller类、Service接口及实现、Mapper接口和XML文件、Model类以及视图页面。通过阅读和分析这些代码,你可以深入...

    sample-java-spring-genericdao:使用 Spring MVC 4.1、Hibernate 4.3 + Generic DAO、Spring Security、Freemarker 的项目示例

    这是一个使用 Spring 4.1 MVC、Core、Security、Generic DAO over Hibernate 4 的示例。目标是展示一个使用 Spring 与 Hibernate 集成的安全 MVC 应用程序,并使用 Generic DAO 框架抽象 DAO 层。 跑前小贴士: ...

    基于Spring4MVC的测试Demo

    "spring-boot-sample-web-jsp"这个文件名暗示了这是一个使用Spring Boot的Web应用示例,其中包含了JSP(JavaServer Pages)技术。JSP是动态网页生成技术,允许我们在HTML页面中嵌入Java代码,实现视图层的动态渲染。...

    spring-mvc:Spring MVC的一个SAMLE项目

    在这个名为 "spring-mvc" 的 SAMLE(可能是“sample”拼写错误)项目中,我们可以深入学习 Spring MVC 的核心概念和工作原理。 1. **MVC 模式** MVC 模式将应用程序分为三个主要组件:模型(Model)、视图(View)...

    springmvc3

    这个压缩包可能包含了运行一个基于Spring MVC 3.0.2和Hibernate3的简单应用所需的所有依赖,例如sample项目,可以作为学习和实践的基础。通过深入理解和实践这些知识点,开发者能够更好地掌握Spring MVC的使用,构建...

    Struts2Spring Sample Project

    Struts2Spring Sample Project是一个整合了Struts2和Spring框架的示例项目,它展示了如何在实际开发中将这两个流行的技术结合使用。Struts2是一个强大的MVC(Model-View-Controller)框架,用于构建可维护性和扩展性...

    ssi (springMVC) 架包

    Spring MVC 是一个基于 Java 的轻量级 Web 开发框架,它是 Spring 框架的一部分,主要用于构建 MVC(Model-View-Controller)模式的 Web 应用程序。在本压缩包中,"ssi" 可能是指 "Spring Server Pages" 或者是用户...

    spring-boot

    4. **Spring MVC**:Spring Boot 默认使用 Spring MVC 实现 Web 功能,理解其工作原理。 5. **Spring Data**:学习如何通过 Spring Data 访问数据库,包括 JPA 和 JDBC。 6. **Actuator**:学习监控和管理应用程序的...

    SpringMVC自定义多视图

    在SpringSample项目中,可能包含了示例代码,演示了如何配置和使用自定义多视图。通过查看源码,你可以更好地理解如何在实际应用中实现这一功能。可能包括配置文件(如spring-servlet.xml)、自定义视图解析器的Java...

    SpringBoo和JSP合成

    下面我们将详细探讨如何在SpringBoot项目中集成JSP,并通过`spring-boot-sample-web-jsp`这个示例来学习相关知识。 首先,SpringBoot默认不支持JSP,因为它推荐使用Thymeleaf、Freemarker等现代模板引擎。但如果你...

    SpringSample2

    然而,现代Spring MVC开发更倾向于使用Thymeleaf或Freemarker等模板引擎,而非传统的JSP。这些模板引擎提供了更丰富的功能和更清晰的语法。在Thymeleaf中,上面的`jsp:getProperty`操作可以转换为: ```html ${user...

    sample-spring-boot:创建一个 Spring Boot 示例

    综上所述,"sample-spring-boot" 示例项目将引导我们了解如何创建一个基础的 Spring Boot 应用,包括如何配置、启动、运行和测试。通过这个项目,我们可以学习到 Spring Boot 的核心特性,并掌握其在 Java 开发中的...

    SpringBoot.Sample:遵循 Spring-Boot 示例

    7. **Thymeleaf 或者 FreeMarker 模板引擎**:Spring Boot 可以配合 Thymeleaf 或 FreeMarker 进行视图渲染,实现 MVC 架构。 8. **Spring Security**:如果需要进行安全控制,Spring Boot 提供了对 Spring ...

Global site tag (gtag.js) - Google Analytics