XSS Protection from Query Strings in Java Looking for input on the code below. Generally, the idea is to take a String representing a URL query string such as param1=blah&amp;param2=blah and encode them to protect against possible XSS attack. Using existing utilities (i.e. UrlEncodedUtils) is not an option.

public static Map&lt;String, List&lt;String&gt;&gt; getParamsFromQueryString(String queryString) throws UnsupportedEncodingException {

    Map&lt;String, List&lt;String&gt;&gt; params = new HashMap&lt;&gt;();


    for (String param : queryString.split("&amp;")) {
        String[] pair = param.split("=");
        String key = ESAPI.encoder().encodeForHTML(URLDecoder.decode(pair[0], "UTF-8"));
        String value = "";
        if (pair.length &gt; 1) {
            value = ESAPI.encoder().encodeForHTML(URLDecoder.decode(pair[1], "UTF-8"));
        }

        // skip ?&amp; and &amp;&amp;
        if ("".equals(key) &amp;&amp; pair.length == 1) {
            continue;
        }

        List&lt;String&gt; values = params.get(key);
        if (values == null) {
            values = new ArrayList&lt;&gt;();
            params.put(key, values);
        }
        values.add(value);
    }

    return params;
}
In addition to RotoRa's answer:

Instead of

    String[] pair = param.split("=");


you should call

    String[] pair = param.split("=", 2);


Otherwise you will trim base64-encoded data, which may happen in some applications, especially if the client forgets to properly encode the = characters.

Instead of a HashMap, use a LinkedHashMap, since that will keep the parameters in the same order as they appeared in the original URL. This makes the code easier to test (you do have unit tests, I hope) and more predictable in general.