DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more

Using Mustache.java Templates With Struts 2

Ricardo Zuasti user avatar by
Ricardo Zuasti
·
May. 27, 12 · Interview
Like (0)
Save
Tweet
Share
9.20K Views

Join the DZone community and get the full member experience.

Join For Free

A friend recently recommended I take a look at the Mustache templating engine. It’s clean, simple and designer friendly, and promotes logic minimization on the template side (I don’t like the term “logic-less”, I don’t think you can get away with absolutely zero logic).

To try it out I decided to build a simple Struts 2 based web app, but I found that there was no out-of-the-box integration between the two. Thankfully both frameworks are easily extendable so I managed to get them playing along quite easily.

Mustache has been ported to a number of platforms (Javascript, Ruby, Python and Java amongst others). The Java implementation (mustache.java) is maintained as an independant project and seems to be quite active.

In order to use Mustache templates as views in my Struts app I decided that creating a new result type was the most elegant approach:

package com.ricardozuasti.mustache;
 
import com.github.mustachejava.*;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.dispatcher.PlainTextResult;
 
public class MustacheResult extends PlainTextResult {
 
    private static final Logger LOG = LoggerFactory.getLogger(MustacheResult.class);
 
    @Override
    protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
        HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
        ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(SERVLET_CONTEXT);
 
        PrintWriter writer = response.getWriter();
 
        // Open a stream to read the template passed to the action
        InputStreamReader reader = new FileReader(servletContext.getRealPath(finalLocation));
 
        if (reader == null) {
            LOG.warn("resource at location ["+finalLocation+"] cannot be obtained (return null) from ServletContext !!! ");
        }
        else {
            // We need to pass the real path of the templates to the Mustache compiler, in order to support nested templates
            String resourceRoot = servletContext.getRealPath(finalLocation);
            resourceRoot = resourceRoot.substring(0, resourceRoot.lastIndexOf("/")+1);
 
            MustacheFactory mf = new DefaultMustacheFactory(new File(resourceRoot));
            Mustache mustache = mf.compile(reader, "mustacheResult");
 
            mustache.execute(writer, invocation.getAction());
 
            reader.close();
        }
 
        writer.flush();
        writer.close();
    }
 
}

I extended the PlainTextResult provided by Struts, using the Mustache compiler to pre-process the specified view resources passed onto the executed Struts action.

You can use any of the executed action bean public attributes in your templates as variables. If you want to add any other Java objects to the Mustache scope, you can modify the mustache.execute() line to receive an Object array with all you need.

After this new result type is included in our app, we must configure it in our struts.xml file and just use it in our actions configuration

...
<result-types>
    <result-type name="mustache" class="com.ricardozuasti.mustache.MustacheResult" />
</result-types>
...
<action name="index" class="com.ricardozuasti.mustache.SomeAction">
    <result type="mustache">/somepage.html</result>
</action>
...

I used the .html extension in the example, but you can use .mustache or whatever you prefer. I rather use .html so the templates can be opened with a regular browser outside of the running app, this facilitates working with the templates for pure HTML/CSS purposes.

Check out the mustache documentation for details on how to create your templates.

 

 

Template

Published at DZone with permission of Ricardo Zuasti, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Secure APIs: Best Practices and Measures
  • Is DevOps Dead?
  • Testing Repository Adapters With Hexagonal Architecture
  • Create Spider Chart With ReactJS

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: