ModalAndView to html string in Spring MVC

Dhanu K :

I need to send a mail with some HTML content,

but HTML content is in JSP file

I need to set data in JSP file for content, for this, I am using ModalAndView with addObject like this

ModelAndView view = new ModelAndView(PageConstants.wwEmail);
view.addObject("title",title);
view.addObject("content",html);
prepareEmailMessage(message, to, title, view.toString());

Am I doing it in the correct way? or is there any other way to do it?

How can I get HTML with populated data?

Dhanu K :

As @user404 mentioned in the comment we can use velocity for this, by taking @Syed Shahul answer as a reference, I have achieved my goal of using templates controller, This is my final solution

use these maven dependencies

<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>

for we need to create a template(.vm) file for this in src/main/resources

then create a 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();

Now we need to generate a template with this velocityEngine

String page = "./ww_email.vm";
Template template = velocityEngine.getTemplate(page);

To pass data to the template we should use VelocityContext

VelocityContext velocityContext = new VelocityContext();
velocityContext.put("title", title);
velocityContext.put("content", html);

Then create a StringWriter to obtain HTML string from template

StringWriter stringWriter = new StringWriter();

Then merge this stringWriter with velocityContext

template.merge(velocityContext, stringWriter);

Finally, you can get HTML string like this

String htmlCodeString = stringWriter.toString()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325498&siteId=1