Thymeleaf 添加 baseUrl 指定根路径
2019-03-25 本文已影响0人
洋洋洒洒_6a20
转载自 www.youngboy.vip
原理
修改@{}对应的处理类StandardLinkBuilder重写computeContextPath方法
修改步骤
step1: 重写 StandardLinkBuilder
public static class BaseUrlLinkBuilder extends StandardLinkBuilder {
private String baseUrl;
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
protected String computeContextPath(IExpressionContext context, String base, Map<String, Object> parameters) {
if(baseUrl==null){
throw new TemplateProcessingException("baseUrl 不能为空");
}
return baseUrl;
}
}
step2: 把BaseUrlLinkBuilder注入模板引擎中
@Bean
public BaseUrlLinkBuilder baseUrlLinkBuilder(TemplateEngine templateEngine){
BaseUrlLinkBuilder baseUrlLinkBuilder = new BaseUrlLinkBuilder();
baseUrlLinkBuilder.setBaseUrl("http://www.youngboy.vip");
templateEngine.setLinkBuilder(baseUrlLinkBuilder);
return baseUrlLinkBuilder;
}
全部代码 方便 copy
@Configuration
public class BaseURLConfig {
@Bean
public BaseUrlLinkBuilder baseUrlLinkBuilder(TemplateEngine templateEngine){
BaseUrlLinkBuilder baseUrlLinkBuilder = new BaseUrlLinkBuilder();
baseUrlLinkBuilder.setBaseUrl("http://wechat1.youngboy.vip/proxy");
templateEngine.setLinkBuilder(baseUrlLinkBuilder);
return baseUrlLinkBuilder;
}
public static class BaseUrlLinkBuilder extends StandardLinkBuilder {
private String baseUrl;
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
protected String computeContextPath(IExpressionContext context, String base, Map<String, Object> parameters) {
if (!(context instanceof IWebContext)) {
throw new TemplateProcessingException(
"Link base \"" + base + "\" cannot be context relative (/...) unless the context " +
"used for executing the engine implements the " + IWebContext.class.getName() + " interface");
}
if(baseUrl==null){
throw new TemplateProcessingException("baseUrl 不能为空");
}
return baseUrl;
}
}
}