[Spring MVC]学习笔记--FreeMarker的使用

还是先贴出该例子存于github上的位置

https://github.com/lemonbar/spring-mvc-freemarker

Sping-Framework 的官方文档简单列出了在spring-mvc中如何使用freemarker, 但是相对来说提供的信息和例子太少, 所以在这给出一个详细的例子.

注:我是在maven基础上进行的构建, 很多解释已经在代码中加了, 所以尽量贴代码.

FreeMarker Site: http://freemarker.org/

1. 整个文件夹结构

src
    main
        java
            com.lemon.spring.controller
                GreetingController
        webapp
            WEB-INF
                ftl
                    footer.ftl
                    header.ftl
                    login.ftl
                    welcome.ftl
                root-context.xml
                web.xml
pom.xml

2. pom.xml内容

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lemon.spring</groupId>
    <artifactId>spring-mvc-freemarker</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring-mvc-freemarker Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.framework.version>4.0.6.RELEASE</spring.framework.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <!--context-support should be included for freemarker bean definition.-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring-mvc-freemarker</finalName>
    </build>
</project>

3. web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/root-context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

4. root-context.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: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.lemon.spring"/>
    <!-- 添加注解驱动 -->
    <mvc:annotation-driven enable-matrix-variables="true"/>
    <!--<context:annotation-config/>-->
    <!-- 允许对静态资源文件的访问 -->
    <mvc:default-servlet-handler />

    <!--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>

</beans>

5. GreetingController.java内容

/*
 * Copyright (c) 2014 General Electric Company. All rights reserved.
 *
 * The copyright to the computer software herein is the property of
 * General Electric Company. The software may be used and/or copied only
 * with the written permission of General Electric Company or in accordance
 * with the terms and conditions stipulated in the agreement/contract
 * under which the software has been supplied.
 */
package com.lemon.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
public class GreetingController {

    @RequestMapping(value = "/greeting/{user}", method = RequestMethod.GET)
    public String greeting(@PathVariable String user, Model model) {
        List<String> userList = Arrays.asList(user.split("-"));
        //userList is the variable name, used in ftl file.
        model.addAttribute("userList", userList);
        return "welcome";
    }

    @RequestMapping(value = "/greeting", method = RequestMethod.POST)
    public ModelAndView greeting(@RequestParam("user") String user) {
        List<String> userList = Arrays.asList(user.split("-"));
        ModelAndView result = new ModelAndView("welcome");
        //userList is the variable name, used in ftl file.
        result.addObject("userList", userList);
        return result;
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

6. welcome.ftl

<html>
<head>
    <title>Welcome!</title>
</head>
<body>
<#include "./header.ftl"/>
<table border="1">
    <tr><th>Name</th><th>Price</th></tr>
    <#list userList as user>
        <tr><th>${user}</th><th>1.0</th></tr>
    </#list>
</table>
<!--use include to include another ftl file content in this file.-->
<#include "./footer.ftl"/>
</body>
</html>

7. login.ftl

<#import "/spring.ftl" as spring/>
<html>
<head>
    <title>Please input your names, seperator with ‘-‘ char.</title>
</head>
<body>
<#include "./header.ftl"/>
<form action="greeting" method="POST">
    Names:
    <input type="text" name="user"/><br>
    <input type="submit" value="submit"/>
</form>
<!--use include to include another ftl file content in this file.-->
<#include "./footer.ftl"/>
</body>
</html>

8. footer.ftl

<hr>
<i>
    Copyright (c) 2014 <a href="http://www.acmee.com">Acmee
    Inc</a>,
    <br>
    All Rights Reserved.
</i>

9. header.ftl

<h1>
    This is header!
</h1>
<hr>

[Spring MVC]学习笔记--FreeMarker的使用

时间: 2024-12-26 13:52:50

[Spring MVC]学习笔记--FreeMarker的使用的相关文章

Spring MVC 学习笔记(二):@RequestMapping用法详解

一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置 <servlet>     <servlet-name>servletName</servlet-name>     <servlet-class>ServletClass</servlet-class> </servlet>

[Spring MVC]学习笔记--DispatcherServlet

在上一篇我们介绍了Servlet,这一篇主要来看一下MVC中用到的DispatcherServlet(继承自HttpServlet). 1. DispatcherServlet在web.xml中被声明. <web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet&l

Spring MVC学习笔记(一)--------准备篇

这一系列笔记将带你一步一步的进入Spring MVC,高手勿喷. 首先你得安装以下的工具: JDK,虽然JDK8已经发布了一段时间了,但是由于我们并不会使用到里面的新特性,所以JDK6以上版本皆可以(需加入到PATH环境变量中): Servlet Container,为了能运行WEB应用程序,因此需要一个Web Container,这里我们建议Tomcat即可: IDE,一个好的IDE不仅能提高你开发的效率,还能降低你学习的成本,我们选择的是IntelliJ: 构建工具,推荐使用Gradle,它

[转]Spring MVC 学习笔记 json格式的输入和输出

Spring mvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用 <!-- json --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.8.1</version>

[Spring MVC]学习笔记--基础Servlet

Servlet是一个用Java编写的应用程序,在服务器上运行,处理请求的信息并将其发送到客户端. Servlet的客户端提出请求并获得该请求的响应. 对于所有的客户端请求,只需要创建Servlet的实例一次(这是和CGI(Common Gateway Interface)的重要区别,CGI是每个请求创建一个新实例),因此节省了大量的内存. Servlet在初始化后即驻留内存中,因此每次作出请求时无需加载. 下面通过一个例子来介绍如何编写一个简单的Servlet. 准备工作: 1. 下载并启动To

[Spring MVC]学习笔记--表单标签的使用

github例子地址: https://github.com/lemonbar/spring-mvc-jsp 效果图 关于spring mvc的标签的讲解, 有一篇blog已经讲的很细了. http://haohaoxuexi.iteye.com/blog/1807330 官方文档地址: http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#view-jsp 而且我在上面的例子

[Spring MVC]学习笔记--@RequestMapping

@RequestMapping是用来将请求的url,映射到整个类,或者里面的方法. @Controller @RequestMapping("/test") public class TestController { private final TestService service; @Autowired public TestController(TestService testService) { this.service = testService; } @RequestMap

[Spring MVC]学习笔记--@Controller

在讲解@Controller之前,先说明一下Spring MVC的官方文档在哪. 可能会有人和我一样,在刚接触Spring MVC时,发现在Spring的网站上找不到Spring MVC这个项目. 这是因为Spring MVC被放到Spring Framework里面了. 你可以打开Spring Framework的reference,里面有一部分是专门介绍Spring MVC的,“V. The Web”. Controller是MVC中的C. 在Spring-MVC中用@Controller来

[Spring MVC]学习笔记--@RequestMapping支持的返回类型

下面针对官方文档列出的支持类型进行举例. (本篇例子存于github上, https://github.com/lemonbar/spring-mvc-resolvingview) 可以直接下载, 也可以在浏览器中打开进行查看(强烈建议看这个, 里面有详细的解释). git clone https://github.com/lemonbar/spring-mvc-resolvingview 准备工作 1. 在WEB-INF下增加一个jsp文件夹, 里面增加两个jsp文件, 为login.jsp和