How to concatenate and sanitize strings in JSTL / EL?

I have a complex set of nested functions that substantially disinfect data.

Suppose I want to fix the firstname-lastname combination that was sanitized, but the names are presented as two separate variables.

I understand that I could just select each variable separately, wrapping each of the many sets of sanitation functions, but this is both inelegant and dangerous: large chunks of hard-to-read, duplicated code that need to synchronize the application lifetime.

In real language, I would write something like this:

${fn:trim(fn:replace(fn:replace(fn:replace(fn:replace(firstname + lastname, ..., ...), ..., ...), ..., ...), ..., ...))} 

(Here, the plus is the blue concatenation operator, javascript '+', PHP '.', Etc.)

It also seems absurd to use a separate statement to simply concatenate variables in advance.

Bottom line: this question has been asked a thousand times on the Internet, but all answers effectively shy away from the question, suggesting an alternative implementation. I want to know if this function exists, and the documentation is worse than trivial.

Please stop my suffering and give me a direct answer.

+6
source share
1 answer

What exactly do you want to disinfect? Special HTML / XML characters such as < , > , etc. To prevent XSS holes? If so, why not just use <c:out> ?

 <c:out value="${firstname} ${lastname}" /> 

If there really is more in the picture, the purest thing would be to reorganize this task into the public static utility method, register it as an EL function, and call it.

eg.

 public final class Functions { private Functions() { // Hide c'tor in utility classes. } public static String sanitizeNames(String firstname, String lastname) { // TODO: Implement. return sanitizedFirstname + sanitizedLastname; } } 

which is registered as follows in the file /WEB-INF/functions.tld

 <?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <display-name>Custom Functions</display-name> <tlib-version>1.0</tlib-version> <uri>http://example.com/functions</uri> <function> <name>sanitizeNames</name> <function-class>com.example.Functions</function-class> <function-signature>java.lang.String sanitizeNames(java.lang.String, java.lang.String)</function-signature> </function> </taglib> 

and is used as follows

 <%@taglib uri="http://example.com/functions" prefix="f" %> ... ${f:sanitizeNames(firstname, lastname)} 
+22
source

Source: https://habr.com/ru/post/907967/


All Articles