I am out putting URLS in my JSP pages and wanted to encode those URLS to avoid cross site scripting , The bets solution I can think about was to create a custom EL function for URL encoding and use it in my jsp pages.
Below is how to do that
${f:urlEncode(anyURL)}
Below is how to do that
Create a class with your function
package com.mycompany.myproject.util;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.jsp.tagext.TagSupport;
@SuppressWarnings("serial")
public class FunctionForJSTL {
/**
* This method will return the encoded URL
* http://stackoverflow.com/questions/5053975/how-to-url-encode-a-string-with-jstl
* From above Stackoverflow link
* URLEncoder.encode() is actually not the correct way to encode a URL. It is the correct way to encode a URL parameter. It changes spaces to + for example. The correct technique is new URI(null, url, null).toASCIIString(), which for example changes spaces to %20.
* @param url
* @return
* @throws URISyntaxException
*/
public static String urlEncode(String url) throws URISyntaxException{
String escapedURL=null;
if(url!=null){
escapedURL =new URI(null, url, null).toASCIIString();
return escapedURL;
}
else
return url;
}
}
Create TLD file put it under WEB-INF
<?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>urlEncode</name>
<function-class>com.mycompany.myproject.util.FunctionForJSTL</function-class>
<function-signature>java.lang.String urlEncode(java.lang.String)</function-signature>
</function>
</taglib>
Use In your JSP
Taglib import statement
<%@taglib uri="/WEB-INF/functions.tld" prefix="f" %>
JSP EL
${f:urlEncode(anyURL)}