简体   繁体   中英

How to handle special characters in query string?

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?

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

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>

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);

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>
String userName="abc&def>ghi<j#kl";
String[] strArr = userName.split("[&$#<>]+");
userName = "";
for (String str : strArr){
   userName += str;
}
System.out.println(userName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM