简体   繁体   中英

How would I ignore a single quotation mark within a string that interacts with my embedded quotation marks?

My problem is found here in my loop that displays the results from my SQL query in my java into HTML

I need to add an "add to cart" link with <a href='?id= id &name= name etc.> But the problem lies in that one of the results the name has a possesive as in "John's Smith".

This single quotation mark is ending my href link and not adding that into the name section of the link.

Any suggestions?

do {    
        
out.println("<tr><td class='col-md-1'> <a href='addcart.jsp?id="+rst.getString(1)+"&name="+rst.getString(2)+"&price="+rst.getString(4)+"'>Add to cart</a></td><td>"+rst.getString(2)+"</td><td>"+rst.getString(3)+"</td><td>"+rst.getString(4)+"</td></tr>");

} while (rst.next());

Thanks in advance!

The best way to handle arbitrary and unknown characters in your href is by using URL Encoding , then it won't matter which quotes you use (single or double) or how your quotes might be nested.

Java has a URLEncoder class specifically to do this.

Typically you'd use it on the query string if the rest of the url is known and fixed. I'd recommend building the query string, url encoding it, and then adding that to your output, something like:

final String query =
  "id=" + rst.getString(1) +
  "&name=" + rst.getString(2) +
  "&price=" + rst.getString(4);

out.println("<tr><td class='col-md-1'> <a href='addcart.jsp?" + 
            URLEncoder.encode(query) +
            "etc. the rest");

This Guide to Java URL Encoding/Decoding may be helpful.

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