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

spring boot  + freemarker 怎么获取contextPath 头疼死我了,网上没一个靠谱的 。我就看看之前博客中的
【Spring Boot使用模板freemarker】好像确实没有介绍到在.ftl文件中如何获取contextPath,这就是本文解决要解决的问题。

本章大纲:

(1)问题的提出;
(2)spring中是如何定义requestContextAttribute的;
(3)Spring Boot应该如何定义呢?
(4)有更好的解决方案嘛?
(5)总结


       接下来我们一起来看下本节的内容:
(1)问题的提出;
       我们有时候需要在freemarker模板文件.ftl中获取contextPath,如果没有配置一些参数的话,那么是无法进行获取的。

(2)spring中是如何定义requestContextAttribute的;
       在spring 中是使用配置文件的方法进行配置指定的,如下:
<property name="requestContextAttribute" value="request"/>
       配置完之后,我们就可以在我们的x.ftl文件中使用如下代码进行引入使用:
${request.contextPath}。

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
/**
*
* @author Angel --守护天使
* @version v.0.1
* @date 2017年1月15日
*/
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{
    @Bean
    public FreeMarkerViewResolver freeMarkerViewResolver() {
        System.out.println("MvcConfig.freeMarkerViewResolver()");
        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setPrefix("");
        resolver.setSuffix(".ftl");
        resolver.setContentType("text/html; charset=UTF-8");
        resolver.setRequestContextAttribute("request");
        return resolver;
    }
}
添加以上的代码之后,就可以在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}

猜你喜欢

转载自lanyan-lan.iteye.com/blog/2403804
今日推荐