Java 正则表达式,小于号和大于号
我有一个用户可以在互联网上输入的字符串,目前它没有针对 XSS 攻击的保护。我希望能够替换 <和>符号。俗称“小于”、“大于”、“尖括号”等。
我确信这个问题已经被问过一百万次了,但我找不到一个简单的答案。我认为正则表达式是前进的方向,但无法弄清楚如何选择这些字符。
I have a string that users are able to enter on the internet, currently it is not protected against XSS attacks. I would like to be able to replace < and > symbols. Commonly known as 'less than', 'more than', 'angle brackets' etc.
I am sure this has been asked a million times but I can't find a simple answer. I assume regex is the way forward but can't work out how to pick these characters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你真的应该使用
StringEscapeUtils.escapeHtml()
来自 Apache Commons Lang 来代替正则表达式。例如,您需要做的就是:防止 XSS 的最佳实践是转义所有 HTML 实体,此方法可以为您处理这些情况。否则,您将编写、测试和维护自己的代码来完成已经完成的事情。有关更多详细信息,请参阅 OWASP XSS(跨站脚本)预防备忘单 。
You really should use
StringEscapeUtils.escapeHtml()
from Apache Commons Lang to instead of regex for this. E.g. all you need to do is:The best practice to protect against XSS is to escape all HTML entities and this method handles those cases for you. Otherwise you'll be writing, testing and maintaining your own code to do what has already been done. See the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet for more details.
Java 正则表达式不需要对尖括号进行任何特殊处理。这应该可以正常工作:
希望有帮助。
-tjw
Java regex shouldn't require any special treatment for angle brackets. This should work fine:
Hope that helps.
-tjw
作为正则表达式的替代方案,您可以使用 Apache Commons 等实用程序类 StringEscapeUtils 类,用于在将 HTML 字符串发回服务器时以及将它们存储在数据库中或将它们作为输出重新发送之前对其进行编码。
As an alternative to regex, you can use a utility class like the Apache Commons StringEscapeUtils class to encode your HTML strings when they are posted back to the server and before storing them in the databse or re-sending them as output.
由于您标记了此 jsp,我想添加在 JSP 中转义 HTML/XML 的正常方法是使用 JSTL< /code> 标记或
fn:escapeXml()
函数。例如,
不需要 Apache Commons Lang。另外,转义实际上应该在视图侧完成,而不是在模型/控制器侧完成。
另请参阅:
Since you tagged this jsp, I'd like to add that the normal approach to escape HTML/XML in JSP is using the JSTL
<c:out>
tag orfn:escapeXml()
function.E.g.
No need for Apache Commons Lang. Plus, escaping should really be done in the view side, not in the model/controller side.
See also: