aws-api-gatewayvelocityapache-velocity

Velocity Template Language: How to import EscapeTool


I am trying to use unurl for my mapping template.

  $url                         -> hello here & there
  $esc.url($url)               -> hello+here+%26+there
  $esc.unurl($esc.url($url))   -> hello here & there

I wrote the following mapping template, but $esc.unurl([...]) doesn't work. I couldn't figure out how to fix it. One reason might be that I am missing an import, but I don't know how to import the EscapeTool properly.

#set($httpPost = $input.path('$').split("&"))
{
#foreach( $kvPair in $httpPost )
 #set($kvTokenised = $kvPair.split("="))
 #if( $kvTokenised.size() > 1 )
   "$kvTokenised[0]" : "$esc.unurl($kvTokenised[1])"#if( $foreach.hasNext ),#end
 #else
   "$kvTokenised[0]" : ""#if( $foreach.hasNext ),#end
 #end
#end
}

Solution

  • You need to add it to tools.xml

    Example tools.xml config (if you want to use this with VelocityView):

    <tools>
      <toolbox scope="application">
        <tool class="org.apache.velocity.tools.generic.EscapeTool"/>
      </toolbox>
    </tools>
    

    Or add it in velocity context using code:

    ModelMap model = new ModelMap();
    model.put("esc", new EscapeTool());
    VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, "template.vm", "UTF-8", model)