Java regex smaller and bigger than a sign

I have a string that users can enter on the Internet, it is currently not protected against XSS attacks. I would like to be able to replace <and> characters. Commonly known as less, more, angle brackets, etc.

I'm sure this has been asked millions of times, but I cannot find a simple answer. I assume that regex is the way forward, but cannot decide how to select these characters.

+5
source share
4 answers

You really should use StringEscapeUtils.escapeHtml()from Apache Commons Lang instead for regex. For instance. all you have to do is:

String escaped = StringEscapeUtils.escapeHtml(input);

XSS HTML, . , , , . . OWASP XSS (Cross Site Scripting) Cheat Sheet .

+8

Java regex . :

myString.replace("<", "less than").replace(">", "greater than");

, .

-tjw

+3

, Apache Commons StringEscapeUtils HTML, ​​ .

+1
source

Since you checked this jsp , I would like to add that the usual approach to HTML / XML exclusion in JSP uses the JSTL <c:out> or tag fn:escapeXml().

eg.

<c:out value="${user.name}" />
<input type="text" name="name" value="${fn:escapeXml(user.name)}" />

No need for Apache Commons Lang. In addition, shielding should indeed be done on the view side, and not on the model / controller side.

See also:

+1
source

All Articles