【问题标题】:Thymeleaf not recognizing attribute from serviceThymeleaf 无法识别服务的属性
【发布时间】:2020-12-24 17:45:09
【问题描述】:

我正在开发两个电子邮件模板,一个将发送确认 URL 以验证用户的帐户,另一个将发送重置密码链接。

激活帐户

<p>Use <a th:href="${confirmationUrl}" target="_blank" rel="noopener">this link</a> to activate your account now</p>

重设密码

<a th:href="${resetPasswordUrl}" target="_blank">Reset password</a>

两个链接都收到来自以下方法的th:href 属性:

此方法发送验证令牌链接以激活帐户

public void sendVerificationToken(User user) {
    String token = jwtTokenService.genEmailVerificationToken(user.getId());
    logger.info("Sending verification token to user. user={} email={} token={}",
            user.getId(), user.getEmail(), token);
    String confirmationUrl = null;
    try {
        confirmationUrl = new URIBuilder(verifyEmailUrl)
                .addParameter(VERIFY_EMAIL_ENDPOINT_PARAM, token)
                .build().toString();
        model.addAttribute("confirmationUrl", confirmationUrl);
    }

    catch (URISyntaxException e) {
        logger.error("URL stored as redirect url for verify email is not valid.");
        throw ErrorFactory.serverError("Error");
    }
    emailService.sendAccountConfirmationEmail(user.getEmail(), confirmationUrl);
}

此方法发送密码重置链接

public void resetPasswordRequest(User user) {
    logger.info("Request for password recovery. email={}",
            user.getEmail());
    String token = jwtTokenService.genPasswordResetToken(user.getId());
    String resetPasswordUrl = null;
    try {
        resetPasswordUrl = new URIBuilder(resetPasswordUrl)
                .addParameter(RESET_PASS_ENDPOINT_PARAM, token)
                .build().toString();
        model.addAttribute("resetPasswordUrl", resetPasswordUrl);
    }
    catch (URISyntaxException e) {
        logger.error("URL stored as target url for reset password email is not valid.");
        throw ErrorFactory.serverError("Error");
    }
    emailService.sendPasswordReset(user.getEmail(), resetPasswordUrl);
}

我试图在 HTML 模板中使用 confirmationUrlresetPasswordUrl 的方法是将模型参数声明为这两个方法之上的类级别属性,然后使用 model.addAttribute("attributeName", attribute)

private Model model;

但由于某种原因,我在模板文件中得到了Cannot resolve 'resetPasswordUrl'Cannot resolve 'confirmationUrl'。就像它无法识别属性一样。

【问题讨论】:

  • 您的sendVerificationToken 方法是在Controller 类中吗?为什么不将模型作为方法参数?

标签: java html spring spring-boot thymeleaf


【解决方案1】:

您是否将模型对象注入到 html 模板中? 因为我在你的问题中看不到这一点。

使用SpringTemplateEngine 并以这种方式注入您的模板变量:

Map<String, Object> variable = objectMapper.convertValue(yourModelObject, Map.class);
Context context = new Context(); //org.thymeleaf.context.Context class
context.setVariables(variable);
html = springTemplateEngine.process("your_template_name", context);

【讨论】:

    【解决方案2】:

    我同意@Srinivasa Raghavan 所说的话。我认为没有必要在邮寄步骤中使用模型对象。

    1 - 如果您发送确认 url 的方法像这样工作就足够了。 您可以调整示例代码以使其更通用。

    public void sendAccountConfirmationEmail(String recipient, String confirmationUrl) {
    
            Context context = new Context();
            context.setVariable("confirmationUrl", confirmationUrl);
    
            MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, "UTF-8");
                messageHelper.setFrom("Test <test@test.com>");
                messageHelper.setTo(recipient);
                messageHelper.setSubject("Active Account");
                String content = templateEngine.process("your_active_account.html", context);            
                messageHelper.setText(content, true);
            };
    
            mailSender.send(mimeMessagePreparator);
        }
    

    2 - 为了处理我们的模板,您将在我们的 Spring 电子邮件配置中配置一个专门为电子邮件处理配置的 TemplateEngine。你可以参考thymeleaf documentation创建TemplateEngine

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2019-12-17
      相关资源
      最近更新 更多