Spring Boot 中使用 Freemarker

Freemarker  是一个模板引擎,它是一种基于模板和要改变的数据来生成输出文本(不一定是HTML 还可以是其他的如邮件和配置文件等)。

在Spring Boot 中使用 Freemarker 只需要在 pom 文件中引入相关的依赖就可以了
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-freemarker</artifactId>  
</dependency>


将我们前面学习搭建的时候的 login.jsp 改一下,改为login.ftl
<html>
<body>
  <p> ${password }</p>
  <p> ${userName }</p>
</body>
</html>


并且将其放于templates 文件夹下

并修改controller 
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hlm.command.UsersCommand;

@Controller
public class UsersController {
    
    @RequestMapping("/index")
    public String index(){
        return "index.html";
    }
        
    @RequestMapping("/sigup")                                                                
    public ModelAndView  sigup(HttpServletRequest req ,ModelAndView  mv){
          mv = mv == null?new ModelAndView():mv;
        
        UsersCommand cmd = new UsersCommand("小明",0,"[email protected]",1,"123456" );
        
         req.getSession().setAttribute("user", cmd);
         mv.addObject("password", cmd.getPassword());
         mv.addObject("userName", cmd.getUserName());
         System.out.println(cmd.getPassword());
         mv.setViewName("/login");
       return mv;
    }
}
其中:mv.setViewName("/login");
处只加模板前缀就行了,因为.ftl会被自动加上的。
运行结果为:


想学习更多的 Freemarker 的知道那可以到其他网站去查询所要的知识,在此主要是学习如何在 Spring Boot 中使用它。

猜你喜欢

转载自blog.csdn.net/mottohlm/article/details/80685632