1

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!

Niblink
  • 33
  • 5

1 Answers1

0

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.

Stephen P
  • 14,422
  • 2
  • 43
  • 67