Spring Boot Freemarker特别篇之contextPath【从零开始学Spring Boot】

springboot+freemarker怎么获取contextPath头疼死我了,网上没一个靠谱的。我就看看之前博客中的

【SpringBoot使用模板freemarker】好像确实没有介绍到在.ftl文件中如何获取contextPath,这就是本文解决要解决的问题。

本章大纲:

(1)问题的提出;

(2)spring中是如何定义requestContextAttribute的;

(3)SpringBoot应该如何定义呢?

(4)有更好的解决方案嘛?

(5)总结

接下来我们一起来看下本节的内容:

(1)问题的提出;

我们有时候需要在freemarker模板文件.ftl中获取contextPath,如果没有配置一些参数的话,那么是无法进行获取的。

(2)spring中是如何定义requestContextAttribute的;

在spring中是使用配置文件的方法进行配置指定的,如下:

<propertyname="requestContextAttribute"value="request"/>

配置完之后,我们就可以在我们的x.ftl文件中使用如下代码进行引入使用:

${request.contextPath}。

(3)SpringBoot应该如何定义呢?

在spring中是使用配置文件的方式,但是我们知道springboot基本上零配置编程的(虽然也支持配置文件的方式),那么我们应该怎么办呢?我们可以之定义一个FreemarkerViewResolver进行指定requestContextPath属性值,具体代码如下:

packagecom.kfit.config;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.web.servlet.config.annotation.EnableWebMvc;

importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

importorg.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

/**

*

*@authorAngel--守护天使

*@versionv.0.1

*@date2017年1月15日

*/

@Configuration

@EnableWebMvc

publicclassMvcConfigextendsWebMvcConfigurerAdapter{

@Bean

publicFreeMarkerViewResolverfreeMarkerViewResolver(){

System.out.println("MvcConfig.freeMarkerViewResolver()");

FreeMarkerViewResolverresolver=newFreeMarkerViewResolver();

resolver.setPrefix("");

resolver.setSuffix(".ftl");

resolver.setContentType("text/html;charset=UTF-8");

resolver.setRequestContextAttribute("request");

returnresolver;

}

}

添加以上的代码之后,就可以在x.ftl文件中使用${request.contextPath}了。

(4)有更好的解决方案嘛?

以上方式虽然也能解决问题,但是总觉得绕了一个圈子,我们原本使用freemarker的时候,我们使用的是在配置文件application.properties文件进行使用的,现在又回到了代码的方式去引入了,那么要思考下我们可不可以在application.properties进行直接指定呢,答案是可以的。我们只需要在application.properties中添加如下配置:

spring.freemarker.request-context-attribute=request

那么就可以在ftl文件中进行使用${request.contextPath}了。

(5)总结

本文说了这么说,其实很简单就两个步骤:

1、在application.properties添加如下信息:

spring.freemarker.request-context-attribute=request

2、在x.ftl文件中进行使用:

${request.contextPath}

BTW:有时候我们为了代码的使用简单,request-context-attribute也会设置为ctx,那么使用的时候就是${ctx.contextPath}

相关推荐