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
日
*/
@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}
最新文章
- 总是多次出现 那个同样的 权限错误 _storage_write_error_, 所以一开始就把机器设好setenforce 0
- I18n问题 国际化
- java中观察者模式Observable和Observer
- JAVA学习之路(环境配置,)
- ubuntu-16.10-desktop-amd64.iso 版本 安装 oracle 11gR2 11.2.0.1 database
- 反射遍历List<;>;泛型类型
- php MVC 及例子解释
- 关于ASSERT(断言)的作用
- Linux系统编程(27)——线程控制
- Linux读取文件路径问题
- PlSql复制角色、权限和添加角色权限
- UpdatePanel Repeater内LinkButton造成页面刷新问题
- [C++]常识回顾
- Android学习:简易图片浏览
- go操作redis
- Qt Multimedia 模块类如何使用?(表格)
- max_result_window
- U3D Input类之键位输入GetKey
- python的Web框架,Django模板变量,过滤器和静态文件引入
- pig cookbook学习