Spring MVC 中的 ModalAndView 到 html 字符串

我需要发送一封包含一些 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?


Qyouu
浏览 54回答 1
1回答

天涯尽头无女友

我们可以使用速度来实现这一点,我已经实现了使用模板控制器的目标,这是我的最终解决方案使用这些 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然后创建一个VelocityEngineVelocityEngine velocityEngine = new VelocityEngine();velocityEngine.setProperty("resource.loader", "class");velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");velocityEngine.init();现在我们需要用这个生成一个模板velocityEngineString page = "./ww_email.vm";Template template = velocityEngine.getTemplate(page);要将数据传递给模板,我们应该使用VelocityContextVelocityContext velocityContext = new VelocityContext();velocityContext.put("title", title);velocityContext.put("content", html);然后创建一个StringWriter从模板中获取HTML字符串StringWriter stringWriter = new StringWriter();然后将其stringWriter与velocityContexttemplate.merge(velocityContext, stringWriter);最后,你可以得到像这样的HTML字符串String htmlCodeString = stringWriter.toString()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java