为了账号安全,请及时绑定邮箱和手机立即绑定

Spring MVC 中的 ModalAndView 到 html 字符串

Spring MVC 中的 ModalAndView 到 html 字符串

Qyouu 2023-09-20 17:07:02
我需要发送一封包含一些 HTML 内容的邮件,但HTML内容在JSP文件中我需要在 JSP 文件中设置内容数据,为此,我将 ModalAndView 与 addObject 一起使用,如下所示ModelAndView view = new ModelAndView(PageConstants.wwEmail);view.addObject("title",title);view.addObject("content",html);prepareEmailMessage(message, to, title, view.toString());我以正确的方式做吗?或者还有其他方法可以做到吗?如何获取包含填充数据的 HTML?
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

我们可以使用速度来实现这一点,我已经实现了使用模板控制器的目标,这是我的最终解决方案


使用这些 Maven 依赖项


<dependency>

    <groupId>org.apache.velocity</groupId>

    <artifactId>velocity</artifactId>

    <version>1.7</version>

</dependency>

<dependency>

    <groupId>org.apache.velocity</groupId>

    <artifactId>velocity-tools</artifactId>

    <version>2.0</version>

</dependency>

因为我们需要为此创建一个模板(.vm)文件src/main/resources


然后创建一个VelocityEngine


VelocityEngine velocityEngine = new VelocityEngine();

velocityEngine.setProperty("resource.loader", "class");

velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

velocityEngine.init();

现在我们需要用这个生成一个模板velocityEngine


String page = "./ww_email.vm";

Template template = velocityEngine.getTemplate(page);

要将数据传递给模板,我们应该使用VelocityContext


VelocityContext velocityContext = new VelocityContext();

velocityContext.put("title", title);

velocityContext.put("content", html);

然后创建一个StringWriter从模板中获取HTML字符串


StringWriter stringWriter = new StringWriter();

然后将其stringWriter与velocityContext


template.merge(velocityContext, stringWriter);

最后,你可以得到像这样的HTML字符串


String htmlCodeString = stringWriter.toString()


查看完整回答
反对 回复 2023-09-20
  • 1 回答
  • 0 关注
  • 51 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信