Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple/Direct/Heredoc way of constructing a HTML string in Java

In python I can construct a HTML string without worrying about escaping special characters like < or " by simply enclosing 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?

like image 834
das_weezul Avatar asked Apr 20 '10 20:04

das_weezul


4 Answers

It can't be done in Java like in Python. However if you are using Eclipse go to Window->Preferences->Java->Editor->Typing The last check box is "Escape text when pasting into a String literal". Check that. Now when you paste when your cursor is between quotation marks it'll be escaped.

like image 69
Adam Avatar answered Nov 12 '22 20:11

Adam


To echo benjismith's trick from a similar question, you can use an alternate character and replace them afterwards:

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

I found it helpful when I was writing tests with 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\"}}";
like image 28
jcadcell Avatar answered Nov 12 '22 20:11

jcadcell


No, but some tools escape it for you when you paste it, like eclipse.

like image 1
Beothorn Avatar answered Nov 12 '22 22:11

Beothorn


For the purpose mentioned, Java Server Pages do the trick even without the tripple """'s :-)

like image 1
rsp Avatar answered Nov 12 '22 20:11

rsp