Search code examples
javajspthymeleafhtml-entities

How to escape forwardslash character in HTML but have it passed correctly to Java web app?


I have IDs for an entity I'm using in my application that look like this:

/6TVYTydu9rBMPuU/zM8Gw==

with all sorts of characters. I need to show these entities and link to them through their ID.

<a href="/myapp/entity/id_goes_here">Id: ${id_goes_here}</a>

This will obviously fail because of the /, link will look like /myapp/entity//6TVYTydu9rBMPuU/zM8Gw== which is obviously wrong for my application. How can I escape the / to the HTML entity &#47; and have it passed to the server as a / and not as the string &#47;?

I'm not using jsp for my view rendering (I'm using thymeleaf), but if there are any solutions for that, they might help.


Solution

  • URL encode the ID before setting it in JSP: http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

    And then URL decode the ID when the server receives it http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLDecoder.html

    E.g

    URLEncoder.encode(id);
    URLEncoder.decode(id);