I am sending emails using amazon java sdk. I have to send html template as mail. I have written a program for this and it is working fine. But now I am storing the whole html code in a single String. But whenever i need to edit the template, I have to edit the program (I mean the String variable). And also I have to take care the special characters like " \ ...etc in that html code. Please suggest me an elegant way to solve this issue.
-
do you mean you have the template hard coded in a java class ? or that you read a file and stiore the content of the file in a String ? i guess the first so just store the html as file and read it when you need it from that filePeter– Peter2012-12-11 07:41:27 +00:00Commented Dec 11, 2012 at 7:41
-
@Peter Yes. Noe I have hard coded it inside my java class. I know it is not a good way.Neeraj– Neeraj2012-12-11 07:44:02 +00:00Commented Dec 11, 2012 at 7:44
-
1As Andrey Adamovich said, use template engine. I recommend Freemarker which is easy to use.faylon– faylon2012-12-11 07:45:04 +00:00Commented Dec 11, 2012 at 7:45
4 Answers
Use a template engine for that and store your template externally either in class path or on a file system. Here is a question that may help you selecting one: https://stackoverflow.com/questions/2381619/best-template-engine-in-java
Comments
Use Apache Common Lang api's StringEscapeUtils#escapeHtml, It escapes the characters in a String using HTML entities and return a new escaped String, null if null string input.
For example:
"US" & "UK"
becomes:
"US" & "UK".
Comments
Check the Apache Velocity Project. You can create template for several things. From it's user-guide page
Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems.
You can use a VTL(Velocity Template Language) . A example from above link
<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
#if ( $customer.hasPurchased($mud) )
<tr>
<td>
$flogger.getPromo( $mud )
</td>
</tr>
#end
#end
</table>
Comments
Better and easiest way is reading the html file line by line using simple file reading operation and append this each line to a single String. And also I found this solution (also a better one, if you are ready to add one more library file to your project) from SO.