Simple / Direct / Heredoc way to build HTML string in Java

In python, I can build an HTML string without worrying about escaping special characters such as <or "by simply inserting the string in triple quotes like:

html_string = """ <html> <body> <p>My text with "quotes" and whatnot!<p> </body> </html> """ 

Is there a similar way to do this in Java?

+21
java string html heredoc convenience-methods
Apr 20 2018-10-20T00:
source share
5 answers

This cannot be done in Java, as in Python. However, if you are using Eclipse, go to Window-> Preferences-> Java-> Editor-> Typing. The last checkbox is "Escape text when pasting into a string literal." Check this. Now when you insert when the cursor is between quotation marks, it will be escaped.

+20
Apr 20 '10 at 21:00
source share

No, but some tools avoid it for you when you insert it, for example in eclipse.

+1
Apr 20 2018-10-20T00:
source share

For this purpose , Java server pages do the trick even without the """ triplex :-)

+1
Apr 20 '10 at 20:59
source share

In Java source code, the double quote is a special character that is used to declare string literals. You cannot have a double quote in a string literal without escaping it.

In general, I will try to avoid such lines of hard code as this in the source code, especially if I find that I am doing this a lot - as you already noted, this is a pain that can be dealt with as a source, and they can most likely change, and in this case you can do without recompilation. If you donโ€™t need to provide runtime parts for text data, you can get away with something as simple as reading data from a properties file, or you can use a template engine like Apache Velocity to keep characteristic data separate and still replace run-time variables - A few examples from the related user guide do just that with HTML.

0
Apr 20 '10 at 20:48
source share

To repeat the benjismith trick from a similar question , you can use an alternate character and replace it later:

 String myString = "using `backticks` instead of quotes".replace('`', '"'); 

I was comfortable when I wrote tests using JSON

 String json = "{`kind`:`file`,`sid`:802,`rid`:5678 ,`attrs`:{`name`:`FILE-WG-2468`}}".replace('`', '"'); // vs String json = "{\"kind\":\"file\",\"sid\":802,\"rid\":5678 ,\"attrs\":{\"name\":\"FILE-WG-2468\"}}"; 
0
Oct 21 '16 at 16:51
source share



All Articles