0

Нужно сделать так чтобы в war файле был класс который обрабатывал статичные страницы шаблонов, как указать шаблонизатору правильный путь к папке с шаблонами, пробовал несколько разных способов как в мануале.

Как правильно прописать в конструкторе инициализацию папки с шаблонами?

private static PageGeneration pageGenerator;
private final Configuration cfg;

public static PageGeneration instance() {
    if (pageGenerator == null)
        pageGenerator = new PageGeneration();
    return pageGenerator;
}

public String getPage(String filename, Map<String, Object> data) {
    Writer stream = new StringWriter();
    try {
        Template template = cfg.getTemplate(filename);
        template.process(data, stream);

    } catch (IOException  | TemplateException e){
        e.printStackTrace();
    }

    return stream.toString();
}

private PageGeneration() {

        cfg = new Configuration();

        cfg.setClassForTemplateLoading(this.getClass(), "/WEB-INF/templates");

} }

В логе томкэта исключение

freemarker.template.TemplateNotFoundException: Template not found for name "user _identefication.html". The name was interpreted by this TemplateLoader: ClassTemplateLoader(resourceLoa derClass=pagegenerator.PageGeneration, basePackagePath="/WEB-INF/templates/").

4
  • С этими загрузчиками вообще мутная тема. Загрузчик this.Class-а скорей всего и не видит WEB-INF. Попробуйте указать такой Thread.currentThread().getContextClassLoader(); Но это вряд ли поможет. Мне не помогло. Если есть возможность сделать свой загрузчик, то сделать его, используя ServletContext : getServletContext().getResourceAsStream("/WEB-INF/templates/user _identefication.html"); Последний приём использовал для загрузки шаблонов Apache Velocity. Самое трудное - сообразить как получить ServletContext где-нибудь, кроме сервлета.
    – Sergey
    14 мая 2016 в 1:29
  • Мне стрим не нужен, мне нужно чтобы он увидел путь, который нужно указать как в мануале на странице фримейкера. который кстати тоже не хочет работать
    – fxrbfg
    16 мая 2016 в 19:08
  • Вместо cfg.setClassForTemplateLoading(Class resourceLoaderClass, String basePackagePath) Вам надо использовать cfg.setServletContextForTemplateLoading(Object servletContext, String path). servletContext получить из request.
    – Sergey
    17 мая 2016 в 0:34
  • Заработало, только как мне теперь передавать сервлет контекст правильно в мой класс, пока напилил так: ' private TemplateWorker(ServletContext context) { cfg = new Configuration(); cfg.setServletContextForTemplateLoading(context,"WEB-INF/templates"); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); '
    – fxrbfg
    17 мая 2016 в 10:27

1 ответ 1

0

Для начала Вам не следует делать инициализацию в конструкторе, отделите ее в метод инициализации:

public class PageGeneration {
    private static PageGeneration pageGenerator;
    private final Configuration cfg;

    public static PageGeneration instance() {
        if (pageGenerator == null)
            pageGenerator = new PageGeneration();
        return pageGenerator;
    }

    public String getPage(String filename, Map<String, Object> data) {
         ...
    }

    private PageGeneration() {
        cfg = new Configuration();
    }

    public void init(String templatesDirectoryPath) {
        configuration.setTemplateLoader(new FileTemplateLoader(new File(templatesDirectoryPath)));
    }   
}

Чтобы выполнить инициализацию конфигурации Freemarker внутри Tomcat потребуется использовать ServletContext для разрешения пути.

Операции с контекстом уместно обработать внутри слушателя:

@WebListener
public class ContextListener implements ServletContextListener {

    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            ServletContext context = sce.getServletContext();
            initTemplater(context);
        } catch (Exception e) {
            log.error(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }


    private void initTemplater(ServletContext context) throws IOException {
        String templatesPath = context.getRealPath("/WEB-INF/templates");
        PageGeneration.instance().init(templatesPath);
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.