美文网首页
Thymeleaf 添加 baseUrl 指定根路径

Thymeleaf 添加 baseUrl 指定根路径

作者: 洋洋洒洒_6a20 | 来源:发表于2019-03-25 16:37 被阅读0次

    转载自 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;
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Thymeleaf 添加 baseUrl 指定根路径

          本文链接:https://www.haomeiwen.com/subject/qidbvqtx.html