springboot中freemarker怎么做文本替换
在Spring Boot中使用Freemarker进行文本替换,首先需要在项目中引入Freemarker依赖。在pom.xml中添加以下依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
然后在应用程序中配置Freemarker模板的位置,可以在application.properties
或application.yml
中添加如下配置:
spring.freemarker.template-loader-path=classpath:/templates/
接下来,在模板文件中使用Freemarker语法进行文本替换。例如,创建一个名为index.ftl
的Freemarker模板文件,内容如下:
<!DOCTYPE html><html><head><title>Welcome</title></head><body><h1>Welcome ${username}!</h1></body></html>
在Spring Boot应用程序中,可以通过ModelAndView对象将数据传递给Freemarker模板进行渲染。示例代码如下:
@Controllerpublic class IndexController {@RequestMapping("/")public ModelAndView index() {ModelAndView modelAndView = new ModelAndView("index");modelAndView.addObject("username", "John");return modelAndView;}}
上面的示例中,username
变量会被替换为John
,最终返回渲染后的HTML页面。通过这种方式,可以实现在Spring Boot中使用Freemarker进行文本替换。