Rectangle 27 45

I think the one of the easiest ways out would be to parse the string returned by URL.getQuery() as

public static Map<String, String> getQueryMap(String query)  
{  
    String[] params = query.split("&");  
    Map<String, String> map = new HashMap<String, String>();  
    for (String param : params)  
    {  
        String name = param.split("=")[0];  
        String value = param.split("=")[1];  
        map.put(name, value);  
    }  
    return map;  
}

You can use the map returned by this function to retrieve the value keying in the parameter name.

Superb it worked like charm thank u v much

This would not work for multivalued parameters. In the following example the EmployeeID parameter has three values: Northwest/Employee Sales Report&rs:Command=Render&EmployeeID=A&EmployeeID=B&EmployeeID=C You could make this work using a multi-valule map implementation instead of HashMap. I don't think the JRE has any, but multi-value map parameter implementations are easily found on the web.

Also a ArrayIndexOutOfBoudndsException would be throw for urls like example.com.com?param or example.com?param=

String value = param.split("=")[1];
String value = param.split(name+"=")[1];

Getting URL parameter in java and extract a specific text from that UR...

java url text-extraction
Rectangle 27 6

You could use the getPath() method of the URL object:

Now, this only brings the actual path. If you need more information (the anchor or the parameters passed as get values), you need to call other accessors of the URL object:

URL url = new URL("https://asd.com/somestuff/another.html?param=value#anchor");
System.out.println(url.getPath());  // prints "/somestuff/another.html"
System.out.println(url.getQuery()); // prints "param=value"
System.out.println(url.getRef());   // prints "anchor"

A possible use to generate the relative URL without much code, based on Hiru's answer:

URL absolute = new URL(url, "/");
String relative = url.toString().substring(absolute.toString().length());
System.out.println(relative); // prints "somestuff/another.html?param=value#anchor"

How to extract the relative url from the absolute url in Java - Stack ...

java
Rectangle 27 38

It doesn't have to be regex. Since I think there's no standard method to handle this thing, I'm using something that I copied from somewhere (and perhaps modified a bit):

public static Map<String, List<String>> getQueryParams(String url) {
    try {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        String[] urlParts = url.split("\\?");
        if (urlParts.length > 1) {
            String query = urlParts[1];
            for (String param : query.split("&")) {
                String[] pair = param.split("=");
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = "";
                if (pair.length > 1) {
                    value = URLDecoder.decode(pair[1], "UTF-8");
                }

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

        return params;
    } catch (UnsupportedEncodingException ex) {
        throw new AssertionError(ex);
    }
}

So, when you call it, you will get all parameters and their values. The method handles multi-valued params, hence the List<String> rather than String, and in your case you'll need to get the first list element.

Maps are a very core and simple concept, so I don't see an issue with them.

This solution does not regard the fragment part of an URL which is appended on the end after a "#". In http urls this part references an internal anchor. So the variable query must be split again at "#" and then the index 0 of the returned array must be further processed.

the part after # is not submitted to the server

@Zapnologica cause of urls like this: bla?asd=5&bsd=6&asd=7

It will raise an ArrayIndexOutOfBoundException for corner cases such as "/foo?="

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 38

It doesn't have to be regex. Since I think there's no standard method to handle this thing, I'm using something that I copied from somewhere (and perhaps modified a bit):

public static Map<String, List<String>> getQueryParams(String url) {
    try {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        String[] urlParts = url.split("\\?");
        if (urlParts.length > 1) {
            String query = urlParts[1];
            for (String param : query.split("&")) {
                String[] pair = param.split("=");
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = "";
                if (pair.length > 1) {
                    value = URLDecoder.decode(pair[1], "UTF-8");
                }

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

        return params;
    } catch (UnsupportedEncodingException ex) {
        throw new AssertionError(ex);
    }
}

So, when you call it, you will get all parameters and their values. The method handles multi-valued params, hence the List<String> rather than String, and in your case you'll need to get the first list element.

Maps are a very core and simple concept, so I don't see an issue with them.

This solution does not regard the fragment part of an URL which is appended on the end after a "#". In http urls this part references an internal anchor. So the variable query must be split again at "#" and then the index 0 of the returned array must be further processed.

the part after # is not submitted to the server

@Zapnologica cause of urls like this: bla?asd=5&bsd=6&asd=7

It will raise an ArrayIndexOutOfBoundException for corner cases such as "/foo?="

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 37

It doesn't have to be regex. Since I think there's no standard method to handle this thing, I'm using something that I copied from somewhere (and perhaps modified a bit):

public static Map<String, List<String>> getQueryParams(String url) {
    try {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        String[] urlParts = url.split("\\?");
        if (urlParts.length > 1) {
            String query = urlParts[1];
            for (String param : query.split("&")) {
                String[] pair = param.split("=");
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = "";
                if (pair.length > 1) {
                    value = URLDecoder.decode(pair[1], "UTF-8");
                }

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

        return params;
    } catch (UnsupportedEncodingException ex) {
        throw new AssertionError(ex);
    }
}

So, when you call it, you will get all parameters and their values. The method handles multi-valued params, hence the List<String> rather than String, and in your case you'll need to get the first list element.

Maps are a very core and simple concept, so I don't see an issue with them.

This solution does not regard the fragment part of an URL which is appended on the end after a "#". In http urls this part references an internal anchor. So the variable query must be split again at "#" and then the index 0 of the returned array must be further processed.

the part after # is not submitted to the server

@Zapnologica cause of urls like this: bla?asd=5&bsd=6&asd=7

It will raise an ArrayIndexOutOfBoundException for corner cases such as "/foo?="

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 4

If you're on Android, you can do this:

Uri uri = Uri.parse(url);
String v = uri.getQueryParameter("v");

Could you explain what package contains this?

@TJ It's in the Android SDK

Getting URL parameter in java and extract a specific text from that UR...

java url text-extraction
Rectangle 27 4

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

import java.net.URL;
    import java.util.regex.*;
public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)
Arrays.toString(tokens)

@paranoid-android +1 rep yeah thanks I know, just forgot what the syntax was without Eclipse open.

Getting URL parameter in java and extract a specific text from that UR...

java url text-extraction
Rectangle 27 3

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.

public static List<NameValuePair> getQueryMap(String query)  
{  
    List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
    String[] params = query.split(Pattern.quote("&"));  
    for (String param : params)
    {
        String[] chunks = param.split(Pattern.quote("="));
        String name = chunks[0], value = null;  
        if(chunks.length > 1) {
            value = chunks[1];
        }
        queryMap.add(new BasicNameValuePair(name, value));
    }
    return queryMap;
}
GET /bottom.gif?e235c08=1509896923&%49%6E%...

Getting URL parameter in java and extract a specific text from that UR...

java url text-extraction
Rectangle 27 13

Not sure how you used find and group, but this works fine:

String params = "depCity=PAR&roomType=D&depCity=NYC";

try {
    Pattern p = Pattern.compile("depCity=([^&]+)");
    Matcher m = p.matcher(params);
    while (m.find()) {
        System.out.println(m.group());
    } 
} catch (PatternSyntaxException ex) {
    // error handling
}

However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");

It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

Just a small remark: instead of using complicating pattern "(?<=depCity=).*?(?=&|$)" to get only values, Im using the first soluiton "depCity=([^&]+)" in combination with m.group(1) to get only values.

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 13

Not sure how you used find and group, but this works fine:

String params = "depCity=PAR&roomType=D&depCity=NYC";

try {
    Pattern p = Pattern.compile("depCity=([^&]+)");
    Matcher m = p.matcher(params);
    while (m.find()) {
        System.out.println(m.group());
    } 
} catch (PatternSyntaxException ex) {
    // error handling
}

However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");

It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

Just a small remark: instead of using complicating pattern "(?<=depCity=).*?(?=&|$)" to get only values, Im using the first soluiton "depCity=([^&]+)" in combination with m.group(1) to get only values.

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 13

Not sure how you used find and group, but this works fine:

String params = "depCity=PAR&roomType=D&depCity=NYC";

try {
    Pattern p = Pattern.compile("depCity=([^&]+)");
    Matcher m = p.matcher(params);
    while (m.find()) {
        System.out.println(m.group());
    } 
} catch (PatternSyntaxException ex) {
    // error handling
}

However, If you only want the values, not the key depCity= then you can either use m.group(1) or use a regex with lookarounds:

Pattern p = Pattern.compile("(?<=depCity=).*?(?=&|$)");

It works in the same Java code as above. It tries to find a start position right after depCity=. Then matches anything but as little as possible until it reaches a point facing & or end of input.

Just a small remark: instead of using complicating pattern "(?<=depCity=).*?(?=&|$)" to get only values, Im using the first soluiton "depCity=([^&]+)" in combination with m.group(1) to get only values.

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 7

If you are developing an Android application, try this:

String yourParam = null;
 Uri uri = Uri.parse(url);
        try {
            yourParam = URLDecoder.decode(uri.getQueryParameter(PARAM_NAME), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }
Uri

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 7

If you are developing an Android application, try this:

String yourParam = null;
 Uri uri = Uri.parse(url);
        try {
            yourParam = URLDecoder.decode(uri.getQueryParameter(PARAM_NAME), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }
Uri

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 7

If you are developing an Android application, try this:

String yourParam = null;
 Uri uri = Uri.parse(url);
        try {
            yourParam = URLDecoder.decode(uri.getQueryParameter(PARAM_NAME), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            exception.printStackTrace();
        }
Uri

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 5

I have three solutions, the third one is an improved version of Bozho's.

new URIBuilder("http://...").getQueryParams()...
// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
    Map<String, String> params = new HashMap<>();

    List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);

    for (NameValuePair nvp : result) {
        params.put(nvp.getName(), nvp.getValue());
    }

    return params;
}
public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length < 2) {
        return params;
    }

    String query = urlParts[1];
    for (String param : query.split("&")) {
        String[] pair = param.split("=");
        String key = URLDecoder.decode(pair[0], "UTF-8");
        String value = "";
        if (pair.length > 1) {
            value = URLDecoder.decode(pair[1], "UTF-8");
        }

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

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

    return params;
}

"improved version of Bozho's"? That's a sacrilege. :)

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 5

I have three solutions, the third one is an improved version of Bozho's.

new URIBuilder("http://...").getQueryParams()...
// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
    Map<String, String> params = new HashMap<>();

    List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);

    for (NameValuePair nvp : result) {
        params.put(nvp.getName(), nvp.getValue());
    }

    return params;
}
public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length < 2) {
        return params;
    }

    String query = urlParts[1];
    for (String param : query.split("&")) {
        String[] pair = param.split("=");
        String key = URLDecoder.decode(pair[0], "UTF-8");
        String value = "";
        if (pair.length > 1) {
            value = URLDecoder.decode(pair[1], "UTF-8");
        }

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

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

    return params;
}

"improved version of Bozho's"? That's a sacrilege. :)

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 5

I have three solutions, the third one is an improved version of Bozho's.

new URIBuilder("http://...").getQueryParams()...
// overwrites duplicates
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public static Map<String, String> readParamsIntoMap(String url, String charset) throws URISyntaxException {
    Map<String, String> params = new HashMap<>();

    List<NameValuePair> result = URLEncodedUtils.parse(new URI(url), charset);

    for (NameValuePair nvp : result) {
        params.put(nvp.getName(), nvp.getValue());
    }

    return params;
}
public static Map<String, List<String>> getQueryParams(String url) throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length < 2) {
        return params;
    }

    String query = urlParts[1];
    for (String param : query.split("&")) {
        String[] pair = param.split("=");
        String key = URLDecoder.decode(pair[0], "UTF-8");
        String value = "";
        if (pair.length > 1) {
            value = URLDecoder.decode(pair[1], "UTF-8");
        }

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

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

    return params;
}

"improved version of Bozho's"? That's a sacrilege. :)

java - How to extract parameters from a given url - Stack Overflow

java regex matcher
Rectangle 27 1

The URL consists of the following elements (note that some optional elements are omitted): 1) scheme 2) hostname 3) [port] 4) path 5) query 6) fragment Using the Java URL API, you can do the following:

URL u = new URL("https://randomsite.org/another/randomPage.html");
System.out.println(u.getPath());

Edit#1 Seeing Chop's answer, in case you have query elements in your URL, such as

?name=foo&value=bar

Using the getQuery() method will not return the resource path, just the query part.

Yep, I was mistaken and made a test to make sure I was not giving bad advice. I also included more details about getQuery() and getRef() before seeing your answer. Great minds think alike. :)

How to extract the relative url from the absolute url in Java - Stack ...

java
Rectangle 27 78

XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as , , , and .

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes amp; instead of and ultimately the enduser would see being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also I'm looking for a Java HTML encoder.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.

An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

@chad: that's not true. It's only the case when you're string-concatenating user-controlled input straight in the SQL/HQL/JPQL query like so "SELECT ... WHERE SOMEVAL = " + someval instead of using parameterized queries as you've shown. No one ORM can safeguard against this kind of developer mistakes.

@BalusC - Doh! I had that reversed. Vulnerable example is: Query query = session.createQuery("SELECT * FROM TABLE WHERE SOMEVAL = " + someval); Using the binding syntax ":" in Hibernate (like my example above) prevents SQL injection. Deleting comment to prevent someone using my bad example.

I think you DO have to validate in the server aswell. All the validation can be bypassed by altering the HTTP parameters. And sometimes, the data that you persist can be consumed by other applications in an enterprise app. Sometimes you dont have access to the views of the other applications so you need to sanitze the input before persisting in the database.

@Guido: you're not understanding the problem.

java - XSS prevention in JSP/Servlet web application - Stack Overflow

java security jsp servlets xss
Rectangle 27 78

XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as , , , and .

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes amp; instead of and ultimately the enduser would see being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also I'm looking for a Java HTML encoder.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.

An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

@chad: that's not true. It's only the case when you're string-concatenating user-controlled input straight in the SQL/HQL/JPQL query like so "SELECT ... WHERE SOMEVAL = " + someval instead of using parameterized queries as you've shown. No one ORM can safeguard against this kind of developer mistakes.

@BalusC - Doh! I had that reversed. Vulnerable example is: Query query = session.createQuery("SELECT * FROM TABLE WHERE SOMEVAL = " + someval); Using the binding syntax ":" in Hibernate (like my example above) prevents SQL injection. Deleting comment to prevent someone using my bad example.

I think you DO have to validate in the server aswell. All the validation can be bypassed by altering the HTTP parameters. And sometimes, the data that you persist can be consumed by other applications in an enterprise app. Sometimes you dont have access to the views of the other applications so you need to sanitze the input before persisting in the database.

@Guido: you're not understanding the problem.

java - XSS prevention in JSP/Servlet web application - Stack Overflow

java security jsp servlets xss