# 2.模板引擎FreeMarker

## 模板引擎FreeMarker

①创建新项目，选择FreeMarker模板引擎和devTools开发工具和web依赖

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTI-iChRplr1cUwpJ%2F2.1.png?generation=1558862975067104\&alt=media)

②新建WebController文件和index模板文件

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTI-kYICpL9xk4n70%2F2.2.png?generation=1558862972216423\&alt=media)

WebController.java

```java
package com.demotm.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/web")
public class WebController {

    @RequestMapping(value = "index")
    public String index(ModelMap map) {
        map.put("title", "freemarker hello word");
        return "index"; // 开头不要加上/，linux下面会出错
    }
}
```

src/main/resources/templates/index.ftl

```markup
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>${title}</h1>
</body>
</html>
```

③启动测试，title已进行了解析

<http://localhost:8080/web/index>

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTI-mFhMRMH402JLh%2F2.3.png?generation=1558862967529862\&alt=media)

## 其他

### 使用Jquery

pox.xml中加入jquery依赖

```markup
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>2.1.4</version>
</dependency>
```

网页中加入即可使用

```javascript
<script type="text/javascript" src="/webjars/jquery/2.1.4/jquery.min.js"></script>
```

### 使用图片或css文件

放入src/main/resources/static 即可

比如

```
src/main/resources/static/images/logo
src/main/resources/static/css/style.css
```

模板中使用：

```markup
<img src="/images/logo.png" />
<link href="/css/style.css" rel="stylesheet" />
```

### 手动直接引入依赖

修改pom.xml,添加如依赖

```markup
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
```
