在 Java 中构造 HTML 字符串的简单/直接/Heredoc 方法
在 python 中,我可以构造一个 HTML 字符串,而不必担心转义特殊字符,例如 <或 " 只需将字符串括在三引号中,例如:
html_string = """
<html>
<body>
<p>My text with "quotes" and whatnot!<p>
</body>
</html>
"""
在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Java 中无法像在 Python 中那样完成。但是,如果您使用 Eclipse,请转至 Window->Preferences->Java->Editor->Typing 最后一个复选框是“粘贴到字符串文字时转义文本”。检查一下。现在,当您粘贴时光标位于引号之间,它将被转义。
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.
为了回应本吉史密斯在类似问题中的技巧,您可以使用替代字符并随后替换它们:
当我正在使用 JSON 编写测试
To echo benjismith's trick from a similar question, you can use an alternate character and replace them afterwards:
I found it helpful when I was writing tests with JSON
不,但是有些工具会在您粘贴时为您转义,例如 eclipse。
No, but some tools escape it for you when you paste it, like eclipse.
出于上述目的,Java Server Pages 执行以下操作即使没有三重
"""
的技巧:-)For the purpose mentioned, Java Server Pages do the trick even without the tripple
"""
's :-)文本块
Java 15 中引入了文本块功能。有关详细信息,请参阅JEP 378:文本块。
将您的材料括在一对三引号字符中。
您的 IDE 可能已更新,可以帮助您编辑文本块。例如,IntelliJ 提供支持。
Text blocks
Text Blocks feature arrived in Java 15. For details, see JEP 378: Text Blocks.
Enclose your material in a pair of triple QUOTATION MARK characters.
Your IDE has likely been updated to be savvy in assisting you with editing text blocks. For example, IntelliJ offers support.
在Java源代码中,双引号是一个特殊字符,用于声明字符串文字。字符串文字中不能有双引号而不进行转义。
一般来说,我会尽量避免像源代码中那样的硬编码字符串,特别是如果我发现自己经常这样做的话 - 正如您所指出的,它们作为源代码处理起来很痛苦,而且很可能改变,在这种情况下你可以不用重新编译。如果您不需要向文本数据提供运行时部分,您可以使用像从属性文件中读取数据这样简单的方法,或者您可以使用像 Apache Velocity 保持字符数据独立,并在运行时仍然替换变量 - 几个链接的用户指南中的示例正是使用 HTML 实现的。
In Java source code, double quote is a special character, used to declare string literals. You cannot have a double quote in a String literal without escaping it.
In general, I would try to avoid hard-coding strings like that in source code, particularly if I found myself doing it a lot - as you've noted, they're a pain to deal with as source and they might be quite likely to change, in which case you could do without recompiling. If you don't need to supply runtime parts to the text data, you could get away with something as simple as reading in the data from a properties file, or you could use a templating engine like Apache Velocity to keep the character data separate and still substitute variables at runtime - several of the examples in the linked user guide do exactly that with HTML.