在 spring boot 项目下使用 freemarker
在之前 jpa-learn 项目的基础上实现。
什么是 Freemarker
FreeMarker 是一款模板引擎:即一种基于模板、用来生成输出文本(任何来自于 HTML格式的文本用来自动生成源代码)的通用工具。它是为 Java 程序员提供的一个开发包,或者说是一个类库。它不是面向最终用户的,而是为程序员提供的一款可以嵌入他们所开发产品
的应用程序。
示例:
- 在 jpa-learn 项目的pom.xml文件中添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
- 在 resources / templates 目录下新建文件 index.ftl
<html>
<body>
welcome ${name} to freemarker!
</body>
</html>
- 在 Controller 中将注解 @RestController 改为 @Controller,需要返回查询数据的接口增加 @ResponseBody:
package com.daqsoft.controller; import com.daqsoft.entity.User; import com.daqsoft.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; /** * @author lxx */ @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/findByName", method = RequestMethod.GET) @ResponseBody public List<User> findByName(String name){ List<User> userList = userService.findByName(name); return userList; } @RequestMapping(value = "/findByAge", method = RequestMethod.GET) @ResponseBody public List<User> findByAge(int age){ List<User> userList = userService.findByAge(age); return userList; } @RequestMapping(value = "/findUser", method = RequestMethod.GET) @ResponseBody public User findUser(long id){ User user = userService.findUser(id); return user; }
// 新增返回 index.ftl @RequestMapping(value = "/index", method = RequestMethod.GET) public String hello(long id, Map<String,Object> map){ User user = userService.findUser(id); map.put("name", user.getName()); return "index"; } }
- 有需要时可以在配置文件 application.yml 中修改 freemarker 默认配置
- 访问路径进行测试:

jpa-learn
posted on 2017-08-22 18:00 Sunday_xiao 阅读(112) 评论(0) 收藏 举报
浙公网安备 33010602011771号