Spring Boot 引入freemarker

72 阅读1分钟

1 Maven引库

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
	<version>2.5.5</version>
</dependency>

application.properties 添加配置

# 模板文件路径,现在配置在resources下的templates文件夹中
spring.freemarker.tempalte-loader-path=classpath:/templates
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl

使用示例

@RestController
@RequestMapping("admin/user")
public class AdminUserController extends BaseController{

    @Autowired
    private UserService userService;

    @GetMapping("/userView")
    public ModelAndView userView() {
        ModelAndView modelAndView = new ModelAndView("user/user");
        return modelAndView;
    }

    @GetMapping("/addUserView")
    public ModelAndView addUserView() {
        ModelAndView modelAndView = new ModelAndView("user/userAdd");
        return modelAndView;
    }

    @GetMapping("/updateUserView")
    public ModelAndView updateUserView(@RequestParam Long id) {
        ModelAndView modelAndView = new ModelAndView("/admin/userUpdate");
        modelAndView.addObject("user", userService.getUserDetail(id));
        return modelAndView;
    }
}