liferay-6liferay-velocity

How to get Server Name and Server Port from Liferay velocity template?


In jsp page we can get Server Name and Server Port by using request.getServerName() and request.getServerPort().`

As we can't get HttpServletRequest from Liferay velocity template, Is there any other way to get both Server Name and Server Port ? Please answer with a small code snippet..


Solution

  • In your Liferay sources you can find com.liferay.portal.velocity.VelocityVariablesImpl.

    This class is placed under portal-impl/src/com/liferay/portal/velocity/VelocityVariablesImpl.java.

    If you check all entries to velocity context (lines like velocityContext.put(String key, Object value)) and specially the ones in the insertVariables method, you'll see that this exposes you httpServletRequest under the name "request".

    Therefore, in your template you access your request object as any other velocity context object with the key $request.

    This object will, then, be usable with all it's methods and properties (if public).

    So just do

    $request.getServerName()
    

    and

    $request.getServerPort()
    

    Furthermore, if you want to set a velocity variable to one of those, just do as follows

    #set ($my_amazing_variable = $request.getServerPort())
    

    You'll then be able to use $my_amazing_variable as any regular velocity litteral.

    Hope this helps.


    NOTA BENE !

    Note that you do not have access to the exact same set of variables and macros under all types of velocity templates in Liferay. There are different sets for