Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape all strings in JSP/Spring MVC

Tags:

I display strings in my JSP this way:

${someString} 

this string may, of course, contain special html characters. Currently it is possible to HTML-inject malicious code (eg. if someString is a javascript include - <script src...>).

How can I make sure that all strings are escaped before printing?

I am using Spring MVC and JSP.

like image 472
Joshua MN Avatar asked Jul 29 '13 09:07

Joshua MN


People also ask

How to escape HTML special characters using Spring MVC?

Use <c:out value="${someString}"/> tag to display Strings. <c:out> escapes HTML characters so that you can avoid cross-site scripting, you can specify that by setting the attribute escapeXml=true . Another advantage is that you can also provide a default value in case the value evaluates to null .

How do you escape HTML special characters in JSP and Java?

The fn:escapeXml() function escapes characters that can be interpreted as XML markup.

How do you escape a forward slash in JSP?

With ${fn:replace(value,'\\','&#92;')} I can escape the \ character, and is working fine.

How does JSP handle special characters?

You want to escape those HTML special characters like < , > , & and " . If it is dynamic text, this is best to be done with JSTL <c:out> tag. Of if you want to set a HTML attribute, the JSTL fn:escapeXml() function is nicer. Simple solution but very powerful.


1 Answers

You can use JSTL core :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

Use <c:out value="${someString}"/> tag to display Strings. <c:out> escapes HTML characters so that you can avoid cross-site scripting, you can specify that by setting the attribute escapeXml=true. Another advantage is that you can also provide a default value in case the value evaluates to null.

You can also use fn:escapeXml() EL function. You need to include JSTL functions for that .

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 

Another possible way , will be build a custom ELResolver.

Enables customization of variable and property resolution behavior for EL expression evaluation.

This blog provides a working example of how it can be done.


For the entire Spring MVC app , you can specify the escaping in the web.xml:

<context-param>    <param-name>defaultHtmlEscape</param-name>    <param-value>true</param-value> </context-param> 

But then the escaping applies only to the spring tags , like :

<form:input path="formField" htmlEscape="true" /> 

Lastly , you can try the third-party library XSSFilter.

like image 58
AllTooSir Avatar answered Sep 29 '22 03:09

AllTooSir