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
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Simple Templating System for Java

Simple Templating System for Java

Kent Johnson user avatar by
Kent Johnson
·
Jul. 07, 08 · Interview
Like (0)
Save
Tweet
Share
11.29K Views

Join the DZone community and get the full member experience.

Join For Free

A templating system allows generating the text for HTML, emails, SQL, etc. without hardcoding the text in Java. This greatly improves the managability of your Java code and makes it much easier to make changes. While the templating system presented below is simple to implement, it still supports variable substitutions, condition logic, loops, etc. This templating system requires Jelly and is implemented in the provided JellyScript Wrapper Class.

Let's say you have a welcome email that should look something like this...

Hello, Kent, thanks for creating a Trendics account at www.trendics.com. 
Your new user name and password is...
   User: kent13600
   Password: my.secret
Be sure to checkout our webmaster tools at http://tools.trendics.com/.

- Trendics Support Team

Instead of hardcoding this text within a Java class, you can use the provided JellyScript Wrapper Class to define a template that looks like this...

Hello<jelly:if test='${!empty FirstName}'>, ${FirstName}</jelly:if>, thanks for creating a
Trendics account at www.trendics.com.
Your new user name and password is...
User: ${UserName}
Password: ${Password}
Be sure to checkout our webmaster tools at http://tools.trendics.com/.
- Trendics Support Team

The LastName and Password variables are simply substituted at the appropriate locations. The <jelly:if test='${!empty FirstName}'>, ${FirstName}</jelly:if> logic is only adding a comma and the FirstName if the FirstName is not blank.

As another example, you can use this templating system to generate SQL...

SELECT *
FROM Employee
WHERE State='${State}'
<jelly:if test='${!empty City}'>
AND City='${City}'
</jelly:if>

In the SQL template above, a State filter parameter is required and a City filter parameter may optionally be included.

The examples above did only simple variable substitution and a bit of conditional logic; however, Jelly supports a whole range of tags supporting various types of logic constructs including loops, creating Java objects, calling methods on Java objects, etc. (see here). The Jelly tags are very similar to JSTL tags commonly used in JSP pages -- this makes the learning curve easy for developers already familiar with JSTL.

Here is an example of the Java code necessary to execute a template...

 public static void main(String[] args) {

if (logger.isLoggable(Level.FINE)) logger.fine("main()");
try {
// Create a template
final String text = "";
text += "Hello<jelly:if test='${!empty FirstName}'>";
text += ", ${FirstName}</jelly:if>, ";
text += "thanks for creating a Trendics account ";
text += "at www.trendics.com. ";
text += "Your new user name and password is...\n";
text += "\n";
text += " User: ${UserName}\n";
text += " Password: ${Password}\n";
text += "\n";
text += "Be sure to checkout the instant website ";
text += "speed check at http://tools.trendics.com/sc.\n";
text += "\n";
text += "- Trendics Support Team\n";

// Create the JellyScript instance
final JellyScript jellyScript = new JellyScript(text);

// Create the variables needed by the template
final Map<String, Object> variables = new HashMap<String, Object>();
variables.put("FirstName", "Kent");
variables.put("UserName", "kent13600");
variables.put("Password", "my.secret");

// Execute the script to merge the variables with the template
final String result = jellyScript.execute(variables);
System.out.println(result);
}
catch (Exception e) {
logger.log(Level.SEVERE, "main()", e);
}
}

Note that defining the template within Java code sort of defeats a key benefit of templating -- you would normally define your templates within an XML configuration file or store the templates in their own files.

If you need a more robust templating solution, take a look at the Apache Velocity Project.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction To OpenSSH
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT
  • Implementing PEG in Java
  • 19 Most Common OpenSSL Commands for 2023

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: