Search code examples
htmljstljspx

how to properly enclose an href that may contain special characters


I have the following code piece

<a href=<c:url value="/admin/main" ><c:param name="key" value="${sessionScope.myvalue}"/></c:url>>Example Link</a>

this works without using href" or href=" or href=' and having nothing surrounding the href - mainly due to it being only paramter. Since myvalue can contain ' or " adding single or double quotes breaks it, adding &quot breaks the link because the local is attached to the start of the url before href since all links in the application are relative. Is this the best way to handle these links? Or is there a better way to enclose the full href without breaking the functionality. usually I would use double quotes if it was not dynamic - it seems wrong to have nothing there


Solution

  • You must html encode the values in the href attribute. Based on your existing <c:url> tag, it looks like you are using the JSTL (Java Standard Tag Library) so you can use the built in escapeXml() function.

    Include the following at the top of your jsp page:

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    

    And then you can call the function like this:

    <c:url var="myUrl" value="/admin/main">
        <c:param name="key" value="${sessionScope.myvalue}"/>
    </c:url>
    
    <a href="${fn:escapeXml(myUrl)}">Example Link</a>