0

I want to handle special characters(&,',",$,#,<,>) in query string in Java and JSP.

Java:

String userName="abc&def>ghi<j#kl";
String url = "/app/ProductAction.do?userName="+userName+"&pwd=test123";
response.sendRedirect(url);

JSP:

<%
    String userName="abc&def>ghi<j#kl";
    String url = "/app/ProductAction.do?userName="+userName+"&pwd=test123";
%>
<a href="<%= url %>"> click here </a>
<a href="javscript:callUrl('<%= url %>')"> forward </a>

How can we handle all these special characters which need to be passed through?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Satya
  • 8,146
  • 9
  • 38
  • 43

5 Answers5

1

try to use url encode and decode. it will handle all the special characters and as well as other non supporting charactors in url

HTTP URL Address Encoding in Java

Community
  • 1
  • 1
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
1

In Java, you should encode every URL parameter with java.net.URLEncoder.

In JSP, you should not use scriptlets. Use the JSP EL, the JSTL, and other custom tags. The JSTL tag to generate URL is <c:url>. It takes care of all this:

<c:url value="/app/ProductAction.do" var="theProperlyEncodedUrl">
    <c:param name="userName" value="${someBean.userName}"/>
    <c:param name="pwd" value="${someBean.pwd}"/>
</c:url>

<a href="<c:out value="${theProperlyEncodedUrl}"/>">click here</a>
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

See the StringEscapeUtils ApiDoc from Apache.

With this class you can escape strings using CSV, HTML, SQL, XML entities or following JAVA, JavaScript rules.

For example, following Java rules you can use this line:

String escapedString = StringEscapeUtils.escapeJava(stringToEscape);

Moreover, in Java you can use the java.net.URL class which encodes properly the url strings. An example, URL myUrl = new URL(stringWithURL);

Charliemops
  • 749
  • 12
  • 30
0

Take a look at the JSTL core taglib:

<c:url value="expression" context="expression"
    var="name" scope="scope">
  <c:param name="expression" value="expression"/>
  ...
</c:url>
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0
String userName="abc&def>ghi<j#kl";
String[] strArr = userName.split("[&$#<>]+");
userName = "";
for (String str : strArr){
   userName += str;
}
System.out.println(userName);
Taha
  • 1,086
  • 1
  • 10
  • 20