简体   繁体   English

将HTML文件存储在Java中的字符串中

[英]Storing html file in a String in java

I am sending emails using amazon java sdk. 我正在使用Amazon Java SDK发送电子邮件。 I have to send html template as mail. 我必须将html模板作为邮件发送。 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. 但是现在我将整个html代码存储在单个String中。 But whenever i need to edit the template, I have to edit the program (I mean the String variable). 但是,每当需要编辑模板时,都必须编辑程序(我的意思是String变量)。 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. 另外,我还必须注意html代码中的特殊字符,例如“ \\ ... etc”。请向我建议一种解决此问题的优雅方法。

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 这是一个可以帮助您选择一个问题的问题: https : //stackoverflow.com/questions/2381619/best-template-engine-in-java

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. 使用Apache Common Lang api的 StringEscapeUtils#escapeHtml ,它使用HTML实体对String中的字符进行转义,并返回一个新的转义String ,如果输入的是空string ,则返回null。

For example: 例如:

"US" & "UK"

becomes: 变为:

"US" & "UK".

Check the Apache Velocity Project . 检查Apache Velocity项目 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. Velocity可用于从模板生成网页,SQL,PostScript和其他输出。 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) . 您可以使用VTL(速度模板语言)。 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>

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. 更好和最简单的方法是使用简单的文件读取操作逐行读取html文件,并将每行附加到单个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. 我也从SO中找到了这种解决方案(如果您准备向项目中再添加一个库文件的话,也是一种更好的解决方案)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM