@Override public String displayTestTemplate(User user) { String applicationPropertyUrl = environment.getProperty("spring.application.url"); String siteName = mailUI.getMessage("mail.site.name"); String greeting = "YOUSA!"; Map<String, Object> model = new Hashtable<>(); model.put("siteName", siteName); model.put("greeting", greeting); model.put("user", user); model.put("applicationPropertyUrl", applicationPropertyUrl); String result = null; try { Template template = fm.getTemplate("tests/test.ftl"); result = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } catch (IOException | TemplateException e) { logger.error("Problem merging test template : " + e.getMessage()); } return result; }
@Override public String getTwitterTemplate(PostMeta postMeta) { String result = null; Map<String, Object> model = new Hashtable<>(); model.put("postMeta", postMeta); String twitterCard = postMeta.getTwitterCardType().name().toLowerCase(); model.put("twitterCardType", twitterCard); try { result = FreeMarkerTemplateUtils .processTemplateIntoString(fm.getTemplate("posts/twitter.ftl"), model); } catch (IOException | TemplateException e) { logger.error("Problem merging Twitter MetaTag template : " + e.getMessage()); } return result; }
@Override public String createRssPostContent(Post post) { String html = null; Map<String, Object> model = new Hashtable<>(); model.put("post", post); model.put("baseurl", applicationSettings.getBaseUrl()); try { Template template = fm.getTemplate("posts/rss_post.ftl"); html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } catch (IOException | TemplateException e) { logger.error("Problem merging post template : " + e.getMessage()); } return html; }
@Override public String createPostHtml(Post post, String templateName) { String html = null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy"); String postCreated = post.getPostDate().format(formatter); Map<String, Object> model = new Hashtable<>(); model.put("post", post); model.put("postCreated", postCreated); model.put("shareSiteName", StringUtils.deleteWhitespace(applicationSettings.getSiteName())); model.put("shareUrl", String.format("%s/post/%s", applicationSettings.getBaseUrl(), post.getPostName())); String displayType = templateName == null ? post.getDisplayType().name().toLowerCase() : templateName; String ftl = String.format("posts/%s.ftl", displayType); try { Template template = fm.getTemplate(ftl); html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); } catch (IOException | TemplateException e) { logger.error("Problem merging post template : " + e.getMessage()); } return html; }
@Override public String createPostAtoZs() { String html = null; String backToTop = mailUI.getMessage("posts.az.page.backtotop"); String azFileName = environment.getProperty("posts.az.file.name"); String azFilePath = applicationSettings.getPostAtoZFilePath(); Map<String, Object> model = new Hashtable<>(); model.put("alphaLinks", postService.getAlphaLInks()); model.put("alphaPosts", postService.getAlphaPosts()); model.put("backToTop", backToTop); try { Template template = fm.getTemplate("posts/az.ftl"); html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); InputStream in = IOUtils.toInputStream(html, "UTF-8"); FileUtils.copyInputStreamToFile(in, new File(azFilePath + azFileName)); } catch (IOException | TemplateException e) { logger.error("Problem creating A-to-Z template or HTML file: " + e.getMessage()); } return html; }
@Async("emailExecutor") public void sendEmail(EmailVerifyCode code, User user) { LOGGER.info("Sending verify email to {} for {}", user.getEmail(), user.getId()); try { mailSender.send(msg -> { msg.setFrom(emailSender()); msg.setRecipients(RecipientType.TO, code.getEmail()); msg.setSubject(subject()); msg.setContent(FreeMarkerTemplateUtils.processTemplateIntoString(fmConfig.getTemplate("email/verify-code.ftl"), model(code, user)), "text/html"); }); } catch (Throwable e) { LOGGER.warn("Couldn't send verify email to {}", user.getEmail(), e); return; } LOGGER.info("Sent verify email to {}", user.getEmail()); }
/** * 发送模板邮件 * 在Spring Boot中也能使用模板引擎来实现模板化的邮件发送。 * 关于模板邮件,SpringBoot 原本是支持 velocity, * 在 1.4 版本后又抛弃了 velocity,暂时只支持 freemaker。 * * <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> */ @Test public void sendTemplateMail() { MimeMessage message = null; try { message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(Sender); helper.setTo(Sender); helper.setSubject("主题:模板邮件"); Map<String, Object> model = new HashMap(); model.put("username", "测试名"); //修改 application.properties 文件中的读取路径 // FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); // configurer.setTemplateLoaderPath("classpath:templates"); //读取 html 模板 Template template = freeMarkerConfigurer.getConfiguration().getTemplate("template.ftl"); String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(html, true); } catch (Exception e) { e.printStackTrace(); } mailSender.send(message); }
private void sendReplyJoinTeamEmail(User user, Team team, TeamStatus status) { final Map<String, String> map = new HashMap<>(); map.put(FIRST_NAME, user.getUserDetails().getFirstName()); map.put(TEAM_NAME, team.getName()); map.put("status", status == TeamStatus.APPROVED ? "approved" : "rejected"); try { String[] to = new String[1]; to[0] = user.getUserDetails().getEmail(); String msgText = FreeMarkerTemplateUtils.processTemplateIntoString(replyJoinTeamRequestTemplate, map); mailService.send(TESTBED_EMAIL, to, "Apply To Join Team " + (status == TeamStatus.APPROVED ? "Approved" : "Rejected"), msgText, false, null, null); } catch (IOException | TemplateException e) { log.warn("{}", e); } }
private void sendApplyJoinTeamEmail(User requester, User owner, Team team) { final Map<String, String> map = new HashMap<>(); map.put(FIRST_NAME, owner.getUserDetails().getFirstName()); map.put(TEAM_NAME, team.getName()); map.put(FULL_NAME, requester.getUserDetails().getFirstName() + " " + requester.getUserDetails().getLastName()); map.put(EMAIL, requester.getUserDetails().getEmail()); map.put(PHONE, requester.getUserDetails().getPhone()); map.put(JOB_TITLE, requester.getUserDetails().getJobTitle()); map.put(INSTITUTION, requester.getUserDetails().getInstitution()); map.put(COUNTRY, requester.getUserDetails().getAddress().getCountry()); try { String[] to = new String[1]; to[0] = owner.getUserDetails().getEmail(); String msgText = FreeMarkerTemplateUtils.processTemplateIntoString(applyJoinTeamRequestTemplate, map); mailService.send(TESTBED_EMAIL, to, "Please Process New Request To Join Your Team", msgText, false, null, null); } catch (IOException | TemplateException e) { log.warn("{}", e); } }
private void sendReplyCreateTeamEmail(User user, Team team, TeamStatus status, String reason) { final Map<String, String> map = new HashMap<>(); map.put(FIRST_NAME, user.getUserDetails().getFirstName()); map.put(TEAM_NAME, team.getName()); map.put("status", status == TeamStatus.APPROVED ? "approved" : "rejected"); if (reason != null) map.put("reason", reason); try { String[] to = new String[1]; to[0] = user.getUserDetails().getEmail(); String[] cc = new String[1]; cc[0] = ADMIN_EMAIL; String msgText = FreeMarkerTemplateUtils.processTemplateIntoString(replyCreateTeamRequestTemplate, map); mailService.send(TESTBED_EMAIL, to, "Apply To Create New Team " + (status == TeamStatus.APPROVED ? "Approved" : "Rejected"), msgText, false, cc, null); } catch (IOException | TemplateException e) { log.warn("{}", e); } }
private void sendApplyCreateTeamEmail(User user, Team team) { final Map<String, String> map = new HashMap<>(); map.put(FIRST_NAME, "NCL Admin"); map.put(TEAM_NAME, team.getName()); map.put(FULL_NAME, user.getUserDetails().getFirstName() + " " + user.getUserDetails().getLastName()); map.put(EMAIL, user.getUserDetails().getEmail()); map.put(PHONE, user.getUserDetails().getPhone()); map.put(JOB_TITLE, user.getUserDetails().getJobTitle()); map.put(INSTITUTION, user.getUserDetails().getInstitution()); map.put(COUNTRY, user.getUserDetails().getAddress().getCountry()); try { String msgText = FreeMarkerTemplateUtils.processTemplateIntoString(applyCreateTeamRequestTemplate, map); mailService.send(TESTBED_EMAIL, ADMIN_EMAIL, "Please Process New Request To Create Team", msgText, false, null, null); } catch (IOException | TemplateException e) { log.warn("{}", e); } }
/** * 返回激活链接 * * @param email email * @return 有3个参数 email password */ public static String getContent(String email, String password, Configuration configuration) { Long now = TimeUtil.getNowOfMills(); Map<String, Object> data = new HashMap<>(10); StringBuilder sb = new StringBuilder("http://localhost:8080/user/validate?email="); sb.append(email); sb.append("&password="); sb.append(password); sb.append("&time="); sb.append(now); data.put("email", email); data.put("url", sb.toString()); data.put("now", TimeUtil.getFormatDate(now, TimeUtil.DEFAULT_FORMAT)); Template template; String readyParsedTemplate = null; try { template = configuration.getTemplate("email.ftl"); readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, data); } catch (Exception e) { e.printStackTrace(); } return readyParsedTemplate; }
private String innerProcess(final String template, final Map<String, Object> context, final Locale locale, final String filetype) throws TemplateNotFoundException { try { final String i18nTemplatePath = getI18nHtmlTemplate(locale, template, filetype); LOGGER.debug("Try to process template: '{}' with locale: '{}'", i18nTemplatePath, locale.getDisplayName(ENGLISH)); final Template loadedTemplate = templateConfiguration.getTemplate(i18nTemplatePath); final Map<String, Object> enrichedContext = enrichtContextWithMessageSource(context, locale); return FreeMarkerTemplateUtils.processTemplateIntoString(loadedTemplate, enrichedContext); } catch (final TemplateNotFoundException tnfe) { // Will be handled by the outer process throw tnfe; } catch (final IOException | TemplateException e) { throw new RuntimeException(e); } }
@RequestMapping(value = "/{account}/{projectName}/{branchName}.svg") public ResponseEntity<String> getBadge(@PathVariable String account, @PathVariable String projectName, @PathVariable String branchName) throws Exception { QBuild b = QBuild.build; Page<Build> buildPage = buildRepository.findAll(b.branch.name.eq(branchName).and(b.branch.project.account.eq(account)).and(b.branch.project.name.eq(projectName)), new QPageRequest(0, 2, b.number.desc())); if (buildPage.getTotalPages() == 0) throw new BadgeUnknownException(); Build latest = buildPage.getContent().get(0); long current = System.currentTimeMillis(); HttpHeaders headers = new HttpHeaders(); // see #7 headers.setExpires(current); headers.setDate(current); return ResponseEntity .ok() .headers(headers) .cacheControl(CacheControl.noCache()) .lastModified(current) .eTag(Long.toString(latest.getId())) .body(FreeMarkerTemplateUtils.processTemplateIntoString(configurer.getConfiguration().getTemplate("badge/mybadge.ftl"), latest)); }
/** * API to get template location and model. * * @param mailMetaData * @param templateLocation * @param model * @throws WizardMailException */ private void sendTextMailWithClasspathTemplate(final MailMetaData mailMetaData, final String templateLocation, final MailContentModel model) throws WizardMailException { LOGGER.info("Entering method sendTextMailWithClasspathTemplate...."); model.add("mailMeta", mailMetaData); try { final String result = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerMailConfiguration .getTemplate(templateLocation), model.getModel()); LOGGER.info("Calling method sendTextMail...."); sendTextMail(mailMetaData, result); } catch (Exception e) { LOGGER.error("Exception occured during sending Email.Email meta deta is " + mailMetaData.toString() + ".Excption is " + e.getMessage(), e); throw new WizardMailException(new StringBuilder().append("Error sending mail: ").append(mailMetaData.toString()) .toString(), e); } LOGGER.info("Mail sent successfully.Exiting method sendTextMailWithClasspathTemplate...."); }
private void transformWithTemplate(PageEntity pageEntity, String api) { try { Template template = new Template(pageEntity.getId(), pageEntity.getContent(), freemarkerConfiguration); ApiModelEntity apiEntity = apiService.findByIdForTemplates(api); Map<String, Object> model = new HashMap<>(); model.put("api", apiEntity); final String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); pageEntity.setContent(content); } catch (IOException | TemplateException ex) { logger.error("An error occurs while transforming page content for {}", pageEntity.getId(), ex); } }
@Profile("!test") @Scheduled(cron = "${slack.kudos.cron.weekly}") public void postWeeklyReport() { Map<String, List<ReportableKudosDto>> kudosByRecipient = kudosFromLastWeekByRecipient(); try { String weeklyReport = FreeMarkerTemplateUtils.processTemplateIntoString( freemarkerConfiguration.getTemplate(WEEKLY_REPORT_TEMPLATE), ImmutableMap.of("kudos", kudosByRecipient) ); log.debug(weeklyReport); ResponseEntity<String> responseEntity = restTemplate.postForEntity( slackKudosWebhookUrl, new SlackWebhookRequest(weeklyReport), String.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { log.info("Weekly kudos report posted to Slack"); } else if (log.isErrorEnabled()) { log.error("An error occurred when posting the report to Slack: " + responseEntity.getBody()); } } catch (IOException | TemplateException e) { log.error("Unable to process report template", e); } }
@Override @NonNull public String mergeTemplateIntoString(final @NonNull String templateReference, final @NonNull Map<String, Object> model) throws IOException, TemplateException { final String trimmedTemplateReference = templateReference.trim(); checkArgument(!isNullOrEmpty(trimmedTemplateReference), "The given template is null, empty or blank"); if (trimmedTemplateReference.contains(".")) checkArgument(Objects.equals(getFileExtension(trimmedTemplateReference), expectedTemplateExtension()), "Expected a Freemarker template file with extension 'ftl', while '%s' was given", getFileExtension(trimmedTemplateReference)); try { final String normalizedTemplateReference = trimmedTemplateReference.endsWith(expectedTemplateExtension()) ? trimmedTemplateReference : trimmedTemplateReference + '.' + expectedTemplateExtension(); return FreeMarkerTemplateUtils.processTemplateIntoString( freemarkerConfiguration.getTemplate(normalizedTemplateReference, Charset.forName("UTF-8").name()), model); } catch (Exception e) { throw new TemplateException(e); } }
@RequestMapping("/") @ResponseBody public String list(Model model, // TODO model should no longer be injected @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy, @RequestParam(required = false, defaultValue = "false") boolean desc, @RequestParam(required = false) String base) throws IOException, TemplateException { securityCheck(base); Path currentFolder = loggingPath(base); List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder); List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc); model.addAttribute("sortBy", sortBy); model.addAttribute("desc", desc); model.addAttribute("files", sortedFiles); model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString()); model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : ""); model.addAttribute("parent", getParent(currentFolder)); model.addAttribute("stylesheets", stylesheets); return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model); }
public void publish(Object message) { String name = null; Map<String, Object> headers = null; Map<String, Object> model = null; if (message instanceof Event) { name = "views/event.ftl"; headers = Collections.singletonMap("type", "event"); model = Collections.singletonMap("event", message); } if (name != null) { try { Template template = freeMarkerConfiguration.getTemplate(name); String body = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); messagingTemplate.convertAndSend("/topic/global", body, headers); } catch (Exception e) { log.warn("Cannot send stomp notification", e); } } }
public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws IOException, TemplateException { FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); fcfb.setTemplateLoaderPath("file:/mydir"); Properties settings = new Properties(); settings.setProperty("localized_lookup", "false"); fcfb.setFreemarkerSettings(settings); fcfb.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) { throw new IllegalArgumentException(location); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); fcfb.afterPropertiesSet(); assertThat(fcfb.getObject(), instanceOf(Configuration.class)); Configuration fc = fcfb.getObject(); Template ft = fc.getTemplate("test"); assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap())); }
public void sendMail(String subject, String templatePath, Map<String, Object> data, String toMail) { try { Setting setting = SettingUtil.getSetting(); JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl)javaMailSender; javaMailSenderImpl.setHost(setting.getSmtpHost()); javaMailSenderImpl.setPort(setting.getSmtpPort()); javaMailSenderImpl.setUsername(setting.getSmtpUsername()); javaMailSenderImpl.setPassword(setting.getSmtpPassword()); MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage(); Configuration configuration = freemarkerManager.getConfiguration(servletContext); Template template = configuration.getTemplate(templatePath); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, data); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8"); mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getShopName()) + " <" + setting.getSmtpFromMail() + ">"); mimeMessageHelper.setTo(toMail); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(text, true); addSendMailTask(mimeMessage); } catch (Exception e) { e.printStackTrace(); } }
protected void dropTableModel(String tpl, freemarker.template.Configuration fcfg, ContentTable ct, boolean script, boolean doUpdate) throws Exception { Template tp = fcfg.getTemplate(tpl); Map model = new HashMap(1); model.put("ct", ct); String mapping_xml = FreeMarkerTemplateUtils.processTemplateIntoString( tp, model); // System.out.println(mapping_xml); // org.hibernate.cfg.Configuration cfg = schemaHelper .makeBaseHibernateConfiguration(); cfg.addXML(mapping_xml); // System.out.println(cfg.buildSettings().getDialect().toString()); // // drop table schemaHelper.dropTables(cfg, script, doUpdate); }
@Test public void testUserInstanceValidation() throws Exception { // setup when(readOnlyUser.getUsername()).thenReturn(username); model.put("user", readOnlyUser); when(instance1.getInstanceId()).thenReturn(instanceId1); when(instance1.getInstanceActivityState()).thenReturn(InstanceActivityState.AMBER); when(instance2.getInstanceId()).thenReturn(instanceId2); when(instance2.getInstanceActivityState()).thenReturn(InstanceActivityState.RED); model.put("instances", Arrays.asList(new ReadOnlyInstance[] { new ReadOnlyInstance(instance1), new ReadOnlyInstance(instance2) })); // act Template template = configuration.getTemplate(templateName); String result = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); System.err.println(result); // assert assertTrue(result.startsWith("<html>\n<head><title>User Instance Validation</title></head>\n<body>")); assertTrue(result.contains("<form action=\"/users/" + username + "/instancevalidation/" + pid + "\" method=\"post\">")); assertTrue(result.contains("<tr style=\"background-color: YELLOW;\">")); assertTrue(result.contains("<td>" + instanceId1 + "</td><td align=\"center\"><input type=\"checkbox\" name=\"validate_" + instanceId1 + "\" value=\"true\"/></td>")); assertTrue(result.contains("<tr style=\"background-color: RED;\">")); assertTrue(result.contains("<td>" + instanceId2 + "</td><td align=\"center\"><input type=\"checkbox\" name=\"validate_" + instanceId2 + "\" value=\"true\"/></td>")); assertTrue(result.endsWith("</body>\n</html>\n")); }
public String getContentFromTemplate(Map<String, Object> model, String templateFileName) { StringBuffer content = new StringBuffer(); try { freeMarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); content.append(FreeMarkerTemplateUtils .processTemplateIntoString(freeMarkerConfig.getTemplate(templateFileName), model)); } catch (Exception e) { e.printStackTrace(); } return content.toString(); }
@Override public String getNoLinksMessage() { String result = null; Map<String, Object> model = new Hashtable<>(); try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/nolinks.ftl"), model); } catch (IOException | TemplateException e) { logger.error("Problem merging No Links template : " + e.getMessage()); } return result; }
@Override public String getNoResultsMessage(String search) { String result = null; Map<String, Object> model = new Hashtable<>(); model.put("search", search); try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/noresults.ftl"), model); } catch (IOException | TemplateException e) { logger.error("Problem merging Quick Search template : " + e.getMessage()); } return result; }
@Override public String getNoLikesMessage() { String result = null; try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/nolikes.ftl"), null); } catch (IOException | TemplateException e) { logger.error("Problem merging NoLikes template : " + e.getMessage()); } return result; }
@Override public String getNoMoreLikeThisMessage() { String result = null; Map<String, Object> model = new Hashtable<>(); try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/nomlts.ftl"), model); } catch (IOException | TemplateException e) { logger.error("Problem merging No MoreLikeThis template : " + e.getMessage()); } return result; }
@Override public String getRobotsTxt() { String result = null; try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("utils/robots.ftl"), null); } catch (IOException | TemplateException e) { logger.error("Problem merging Robots.txt template : " + e.getMessage()); } return result; }
@Override public String getFileUploadingScript() { String result = null; try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("utils/fileuploading.ftl"), null); } catch (IOException | TemplateException e) { logger.error("Problem merging fileuploading template : " + e.getMessage()); } return result; }
@Override public String getFileUploadedScript() { String result = null; try { result = FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("utils/fileuploaded.ftl"), null); } catch (IOException | TemplateException e) { logger.error("Problem merging fileuploaded template : " + e.getMessage()); } return result; }
public String print( @NotNull final Object data, @NotNull final String templateName ) throws IOException, TemplateException { configuration.setClassForTemplateLoading(this.getClass(), templatePath); Template template = configuration.getTemplate(templateName); return FreeMarkerTemplateUtils.processTemplateIntoString(template, data); }
@Test @SuppressWarnings("rawtypes") public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception { FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); fcfb.setTemplateLoaderPath("file:/mydir"); Properties settings = new Properties(); settings.setProperty("localized_lookup", "false"); fcfb.setFreemarkerSettings(settings); fcfb.setResourceLoader(new ResourceLoader() { @Override public Resource getResource(String location) { if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) { throw new IllegalArgumentException(location); } return new ByteArrayResource("test".getBytes(), "test"); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } }); fcfb.afterPropertiesSet(); assertThat(fcfb.getObject(), instanceOf(Configuration.class)); Configuration fc = fcfb.getObject(); Template ft = fc.getTemplate("test"); assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap())); }
/** * 生成HTML字符串 * * @param content : 页面传参 * @param templateName : 模板名称路径,相对于模板目录 */ public static String generateString(Map<?, ?> content, String templateName) { String htmlText = ""; try { // 通过指定模板名获取FreeMarker模板实例 Template tpl = loadConfig().getConfiguration().getTemplate(templateName); htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, content); } catch (Exception e) { e.printStackTrace(); } return htmlText; }