org.thymeleaf.context.Context Java Examples
The following examples show how to use
org.thymeleaf.context.Context.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailService.java From tutorial with MIT License | 6 votes |
private String getMailBodyFromTemplate(String templateName, Map<String, Object> vars){ ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("email-templates/"); //模板所在目录,相对于当前classloader的classpath。 resolver.setSuffix(".html"); //模板文件后缀 TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(resolver); Context context = new Context(); for(Iterator<String> iterator = vars.keySet().iterator(); iterator.hasNext();){ String key = iterator.next(); context.setVariable(key, vars.get(key)); } StringWriter writer = new StringWriter(); templateEngine.process("example", context, writer); return writer.toString(); }
Example #2
Source File: SpringbootMailApplication.java From springBoot with MIT License | 6 votes |
@GetMapping("/") public String index() throws MessagingException { //简单邮件 springBootMailService.sendSimpleMail("[email protected]","Simple Mail","第一封简单邮件"); //HTML格式邮件 Context context = new Context(); context.setVariable("username","我的小号"); springBootMailService.sendHtmlMail("[email protected]","HTML Mail",templateEngine.process("mail/mail",context)); //HTML格式邮件,带附件 Context context2 = new Context(); context2.setVariable("username","我的小号(带附件)"); ArrayList<File> files = new ArrayList<>(); //File对象 files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试.txt")); files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试2.txt")); springBootMailService.sendAttachmentsMail("[email protected]","Attachments Mail",templateEngine.process("mail/attachment",context2),files); return "欢迎访问 springboot-mail,邮件发送成功!"; }
Example #3
Source File: MailServiceTest.java From SpringBoot-Home with Apache License 2.0 | 6 votes |
/** * 测试模版邮件邮件 */ @Test public void sendTemplateMail() throws MessagingException { Mail mail = new Mail(); // mail.setReceiver("[email protected]"); mail.setReceiver("[email protected]"); mail.setSubject("测试模版邮件邮件"); //创建模版正文 Context context = new Context(); // 设置模版需要更换的参数 context.setVariable("verifyCode", "6666"); mail.setEmailTemplateContext(context); // 模版名称(模版位置位于templates目录下) mail.setEmailTemplateName("emailTemplate"); mailService.sendTemplateMail(mail); }
Example #4
Source File: HasAllPermissionsTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test @Parameters(source = HasAllPermissions.ShouldRenderForUser.class) public void itShouldRenderOnUser(TestUsers user) { Subject subjectUnderTest = createAndLoginSubject(user); boolean hasAnyFeatures = hasAllFeaturesSanityCheck(subjectUnderTest); assertThat("User has all features", hasAnyFeatures); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("HASALLPERMISSIONS_ATTRIBUTE_STATIC")); assertThat(result, containsString("HASALLPERMISSIONS_ELEMENT_STATIC")); subjectUnderTest.logout(); }
Example #5
Source File: ThymeleafTest.java From ext-opensource-netty with Mozilla Public License 2.0 | 6 votes |
public static void testB() { ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); //模板所在目录,相对于当前classloader的classpath。 resolver.setPrefix("static/"); ///模板文件后缀 // resolver.setSuffix(".html"); // resolver.setCacheable(false);//设置不缓存 // resolver.setTemplateMode("HTML5"); TemplateEngine engine = new TemplateEngine(); engine.setTemplateResolver(resolver); Context context = new Context(); context.setVariable("socketurl", "ws"); System.out.println(engine.process("websocket.html", context)); }
Example #6
Source File: EmailAction.java From spring-boot-examples with Apache License 2.0 | 6 votes |
@PostMapping(value = "html_with_template") public String sendHtmlByTemplate(String msg, String email) { if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) { return "请输入要发送消息和目标邮箱"; } try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true); messageHelper.setFrom(sendName); messageHelper.setTo(email); messageHelper.setSubject("使用HTML模板文件发送邮件"); Context context = new Context(); context.setVariable("msg", msg); messageHelper.setText(templateEngine.process("EmailTemplate", context), true); mailSender.send(message); return "发送成功"; } catch (MessagingException e) { e.printStackTrace(); return "发送失败:" + e.getMessage(); } }
Example #7
Source File: ShiroDialectTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void testPrincipal() { Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); setSubject(subjectUnderTest); Context context = new Context(); String result; // Guest user result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertNull(subjectUnderTest.getPrincipal()); // sanity assertFalse(result.contains("shiro:")); assertFalse(result.contains("DEFPRINCIPAL1")); assertFalse(result.contains("DEFPRINCIPAL2")); // Logged in user subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1)); assertEquals(USER1, subjectUnderTest.getPrincipal()); // sanity result = templateEngine.process(TEST_TEMPLATE_PATH, context); assertFalse(result.contains("shiro:")); assertTrue(result.contains("DEFPRINCIPAL1<span>" + USER1 + "</span>DEFPRINCIPAL1")); assertTrue(result.contains("DEFPRINCIPAL2" + USER1 + "DEFPRINCIPAL2")); subjectUnderTest.logout(); }
Example #8
Source File: EmailUtilTest.java From SpringBoot-Home with Apache License 2.0 | 6 votes |
/** * 工具方法测试 * @throws MessagingException */ @Test public void sendMail2() throws MessagingException { MailDomain mail = new MailDomain(); mail.setReceiver("[email protected]"); mail.setSubject("测试模版邮件邮件"); //创建模版正文 Context context = new Context(); // 设置模版需要更换的参数 context.setVariable("verifyCode", "6666"); mail.setEmailTemplateContext(context); // 模版名称(模版位置位于templates目录下) mail.setEmailTemplateName("emailTemplate"); mail.setIsTemplate(true); emailUtil.sendMail(mail); }
Example #9
Source File: TemplateUtilsTest.java From SkaETL with Apache License 2.0 | 6 votes |
@Test public void astext() { StringTemplateResolver templateResolver = new StringTemplateResolver(); templateResolver.setOrder(1); templateResolver.setTemplateMode(TemplateMode.TEXT); // TODO Cacheable or Not ? templateResolver.setCacheable(false); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); Context context = new Context(); context.setVariable("mavar","cela"); String process = templateEngine.process("ceci [[${mavar}]]", context); assertThat(process).isEqualTo("ceci cela"); String notInterpreted = templateEngine.process("ceci <span th:text=\"${mavar}\"></span>", context); assertThat(notInterpreted).isEqualTo("ceci <span th:text=\"${mavar}\"></span>"); }
Example #10
Source File: TemplatingEngine.java From EDDI with Apache License 2.0 | 6 votes |
@Override public String processTemplate(String template, Map<String, Object> dynamicAttributesMap, TemplateMode templateMode) throws TemplateEngineException { final Context ctx = new Context(Locale.ENGLISH); dynamicAttributesMap.forEach(ctx::setVariable); try { if (containsTemplatingControlCharacters(template)) { return getTemplateEngine(templateMode).process(template, ctx); } else { return template; } } catch (TemplateInputException e) { String message = "Error trying to insert context information into template. " + "Either context is missing or reference in template is wrong!"; throw new TemplateEngineException(message, e); } }
Example #11
Source File: WisdomTemplateEngineTest.java From wisdom with Apache License 2.0 | 6 votes |
@Test public void testJavaScript() { TemplateEngine engine = createWisdomEngine(); engine.initialize(); Context context = new Context(); context.setVariable("test", "test"); FakeRouter router = new FakeRouter(); Controller controller = new FakeController(); router.addController(controller); Assets assets = mock(Assets.class); context.setVariable(Routes.ROUTES_VAR, new Routes(router, assets, controller)); String processed = engine.process("templates/javascript.thl.html", context); assertThat(processed).containsIgnoringCase("var t = 'test';"); assertThat(processed).containsIgnoringCase("var url = '/';"); assertThat(processed).containsIgnoringCase("$(document).ready(function () {"); }
Example #12
Source File: EmailController.java From SpringAll with MIT License | 6 votes |
@RequestMapping("sendTemplateEmail") public String sendTemplateEmail(String code) { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("[email protected]"); // 接收地址 helper.setSubject("邮件摸板测试"); // 标题 // 处理邮件模板 Context context = new Context(); context.setVariable("code", code); String template = templateEngine.process("emailTemplate", context); helper.setText(template, true); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } }
Example #13
Source File: MailNotifier.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() -> { Context ctx = new Context(); ctx.setVariables(additionalProperties); ctx.setVariable("baseUrl", this.baseUrl); ctx.setVariable("event", event); ctx.setVariable("instance", instance); ctx.setVariable("lastStatus", getLastStatus(event.getInstance())); try { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name()); message.setText(getBody(ctx).replaceAll("\\s+\\n", "\n"), true); message.setSubject(getSubject(ctx)); message.setTo(this.to); message.setCc(this.cc); message.setFrom(this.from); mailSender.send(mimeMessage); } catch (MessagingException ex) { throw new RuntimeException("Error sending mail notification", ex); } }); }
Example #14
Source File: MailService.java From ml-blog with MIT License | 6 votes |
@Async public void sendEmail(String toEmail,String subject, String content) throws Exception { Context con = new Context(); con.setVariable("content", content); String emailtext = templateEngine.process("portal/mail.html", con); MimeMessage message = this.javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); InternetAddress from = new InternetAddress(); from.setAddress(this.mailProperties.getUsername()); from.setPersonal(commonMap.get("blogName").toString(), "UTF-8"); helper.setFrom(from); helper.setTo(toEmail); helper.setSubject(subject); helper.setText(emailtext, true); this.javaMailSender.send(message); log.info("发送邮件内容:{}",content); }
Example #15
Source File: HasPermissionTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 6 votes |
@Test public void itShouldRenderForUserAlice() { TestUsers user = TestUsers.ALICE; Subject subjectUnderTest = createAndLoginSubject(user); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("PERM_A_ATTRIBUTE_STATIC")); assertThat(result, containsString("PERM_A_ELEMENT_STATIC")); assertThat(result, containsString("PERM_B_ATTRIBUTE_STATIC")); assertThat(result, containsString("PERM_B_ELEMENT_STATIC")); assertThat(result, containsString("PERM_C_ATTRIBUTE_STATIC")); assertThat(result, containsString("PERM_C_ELEMENT_STATIC")); subjectUnderTest.logout(); }
Example #16
Source File: OrderController.java From jcart with MIT License | 6 votes |
protected void sendOrderStatusUpdateEmail(Order order) { try { // Prepare the evaluation context final Context ctx = new Context(); ctx.setVariable("order", order); // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process("order-status-update-email", ctx); emailService.sendEmail(order.getCustomer().getEmail(), "QuilCartCart - Order Status Update", htmlContent); } catch (JCartException e) { logger.error(e); } }
Example #17
Source File: MailContentBuilder.java From auth-server with Apache License 2.0 | 5 votes |
/** * <p> * Populate email template with custom message. * </p> */ public String build(String message, String link) { Context context = new Context(); context.setVariable("message", message); context.setVariable("link", link); return templateEngine.process("mail/mail", context); }
Example #18
Source File: HasAllRolesTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 5 votes |
@Test public void itShouldRenderForUserBob() { TestUsers user = TestUsers.BOB; Subject subjectUnderTest = hasAllRolesSanityCheck(createAndLoginSubject(user)); String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, containsString("HASALLROLES_ATTRIBUTE_STATIC")); assertThat(result, containsString("HASALLROLES_ELEMENT_STATIC")); subjectUnderTest.logout(); }
Example #19
Source File: RedisServiceTest.java From Jantent with MIT License | 5 votes |
@Test public void test(){ Context context = new Context(); PageInfo<ContentVo> articles = contentService.getContents(1, 10); List<MetaDto> categories = metaService.getMetaList(Types.CATEGORY.getType(), null, WebConst.MAX_POSTS); context.setVariable("categories", categories); context.setVariable("articles", articles); String html = templateEngine.process("themes/jantent/index",context); System.out.println(html); }
Example #20
Source File: MailService.java From gpmr with Apache License 2.0 | 5 votes |
@Async public void sendCreationEmail(User user, String baseUrl) { log.debug("Sending creation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, baseUrl); String content = templateEngine.process("creationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #21
Source File: MailService.java From tutorials with MIT License | 5 votes |
@Async public void sendActivationEmail(User user) { log.debug("Sending activation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("activationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #22
Source File: LoginRegisterController.java From DouBiNovel with Apache License 2.0 | 5 votes |
@RequestMapping(method = RequestMethod.POST,value = "/sendRegisterMail") @ResponseBody public MvcResult sendRegisterMail(String email, HttpSession session){ MvcResult result = MvcResult.create(); if (StringUtils.isEmpty(email)){ result.setSuccess(false); result.setMessage("发送验证码失败:邮箱不能为空"); }else if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) { result.setSuccess(false); result.setMessage("发送验证码失败:邮箱格式不正确"); }else if (userService.getByPhoneOrCodeOrEmail(email)!=null){ result.setSuccess(false); result.setMessage("发送验证码失败:该邮箱已被注册"); }else { try { String code = String.format("%5d",new Random().nextInt(100000)); SystemSetting setting = systemSettingService.getSetting(); Context context = new Context(); context.setVariable("siteName", setting.getSitename()); context.setVariable("mail",email); context.setVariable("code",code); String emailContent = templateEngine.process("mail/register_mail", context); mailService.sendHtmlMail(email,String.format("欢迎注册 %s ",setting.getSitename()),emailContent); session.setAttribute(Const.session.REGISTER_CODE,code); session.setAttribute(Const.session.REGISTER_EMAIL,email); }catch (Exception e){ result.setSuccess(false); if (StringUtils.isEmpty(e.getMessage())){ result.setMessage("发送验证码失败:原因未知"); }else { result.setMessage("发送验证码失败:"+e.getMessage()); } } } return result; }
Example #23
Source File: AuthenticatedTagTest.java From thymeleaf-extras-shiro with Apache License 2.0 | 5 votes |
@Test public void itShouldNotRenderAuthenticatedTagContentOnGuestUser() { Subject subjectUnderTest = createSubject(); setSubject(subjectUnderTest); checkArgument(!subjectUnderTest.isAuthenticated()); // sanity String result = processThymeleafFile(FILE_UNDER_TEST, new Context()); assertThat(result, not(containsString("shiro:"))); assertThat(result, not(containsString("AUTHENTICATED_ATTRIBUTE"))); assertThat(result, not(containsString("AUTHENTICATED_ELEMENT"))); }
Example #24
Source File: _MailService.java From jhipster-ribbon-hystrix with GNU General Public License v3.0 | 5 votes |
@Async public void sendPasswordResetMail(User user, String baseUrl) { log.debug("Sending password reset e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable("user", user); context.setVariable("baseUrl", baseUrl); String content = templateEngine.process("passwordResetEmail", context); String subject = messageSource.getMessage("email.reset.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #25
Source File: _MailService.java From jhipster-ribbon-hystrix with GNU General Public License v3.0 | 5 votes |
@Async public void sendCreationEmail(User user, String baseUrl) { log.debug("Sending creation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable("user", user); context.setVariable("baseUrl", baseUrl); String content = templateEngine.process("creationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #26
Source File: MailService.java From tutorials with MIT License | 5 votes |
@Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("passwordResetEmail", context); String subject = messageSource.getMessage("email.reset.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #27
Source File: MailService.java From spring-boot-ignite with Apache License 2.0 | 5 votes |
public boolean sendAlert(AlertEntry alertEntry, List<String> emails, String mailTemplate){ logger.debug("Sending alert e-mail to '{}'", emails.toString()); Locale locale = Locale.getDefault(); Context context = new Context(locale); context.setVariable("alert", alertEntry); String content = templateEngine.process(mailTemplate, context); return sendEmail(mailFromBpo, emails, "New Application ticket has been created", content); }
Example #28
Source File: MailService.java From jhipster-online with Apache License 2.0 | 5 votes |
@Async public void sendEmailFromTemplate(User user, String templateName, String titleKey) { if (user.getEmail() == null) { log.debug("Email doesn't exist for user '{}'", user.getLogin()); return; } Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); sendEmail(user.getEmail(), subject, content, false, true); }
Example #29
Source File: PermissionsMother.java From thymeleaf-extras-shiro with Apache License 2.0 | 5 votes |
private static Object[] paramsForUser(TestUsers user) { return $( $(user, new Context()), $(user, contextWithPermission(null)), $(user, contextWithPermission("foobar")), $(user, contextWithPermission("foo, bar")), $(user, contextWithPermission(Sets.newHashSet())), $(user, contextWithPermission(Sets.newHashSet( "foo", "bar", "foo, bar" )))); }
Example #30
Source File: UserService.java From wallride with Apache License 2.0 | 5 votes |
@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true) public UserInvitation inviteAgain(UserInvitationResendRequest form, BindingResult result, AuthorizedUser authorizedUser) throws MessagingException { LocalDateTime now = LocalDateTime.now(); UserInvitation invitation = userInvitationRepository.findOneForUpdateByToken(form.getToken()); invitation.setExpiredAt(now.plusHours(72)); invitation.setUpdatedAt(now); invitation.setUpdatedBy(authorizedUser.toString()); invitation = userInvitationRepository.saveAndFlush(invitation); Blog blog = blogService.getBlogById(Blog.DEFAULT_ID); String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/_admin/signup") .queryParam("token", invitation.getToken()) .buildAndExpand().toString(); final Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("websiteTitle", websiteTitle); ctx.setVariable("authorizedUser", authorizedUser); ctx.setVariable("signupLink", signupLink); ctx.setVariable("invitation", invitation); final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject(MessageFormat.format( messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()), authorizedUser.toString(), websiteTitle)); message.setFrom(authorizedUser.getEmail()); message.setTo(invitation.getEmail()); final String htmlContent = templateEngine.process("user-invite", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); return invitation; }