开发者

How to read a java map from request and iterate over it in a velocity template?

开发者 https://www.devze.com 2023-03-14 14:38 出处:网络
Problem: I am working on Liferay 6.0.5. I want to read a java m开发者_Go百科ap from request and iterate over it in a velocity template. The velocity is not able to read it as map rather it is taken as

Problem: I am working on Liferay 6.0.5. I want to read a java m开发者_Go百科ap from request and iterate over it in a velocity template. The velocity is not able to read it as map rather it is taken as String value.

JSP Code: 1. Reading categories:

List<AssetCategory> curCategories = assetEntry.getCategories();
Map<String, String> catgrMap=new HashMap<String, String>();
String temp="";
String key=null;
for (AssetCategory category : curCategories) {
    key=(AssetVocabularyServiceUtil.getVocabulary(category.getVocabularyId())).getName();
    if(!temp.equalsIgnoreCase(key)){
       catgrMap.put(key,category.getName());
       temp=key;
    }else{
       String val=(String)catgrMap.get(key);
       val=val+","+category.getName();
       catgrMap.put(key,val);
       temp=key;
    }   
}
  1. Setting Map in request

    request.setAttribute("categoryMap",catgrMap);
    

What I want: I want to iterate over this catgrMap and read its keys and values. Here is the steps:

  1. Get map from request :

    #set ($categoryMap= $request.get('attributes').get('categoryMap'))
    
  2. Iterate over map - There are many ways to iterate over a map in velocity and here are some of them. 2.1

    #foreach ($mapEntry in $categoryMap.entrySet())
    <tr>
      <td>$mapEntry.key</td>
        <td>$mapEntry.value</td>
    

    #end

    2.2
    
    #set( $keys = $categoryMap.keySet() )
    

    #foreach( $key in $keys ) $key $categoryMap[$key] #end

    2.3
    #set ($map = $categoryMap.getMap() )
    
    #foreach ($mapEntry in $map.entrySet())
    

    $mapEntry.key $mapEntry.value #end

  3. The Roadblock: The problem is not how we are iterating, its how the velocity reads the map from request. It reads the map as String object so iteration is not possible. The ${categoryMap.class.name} returns String and not Map.

What are the possible ways to pass a map to velocity and iterate over it? We are not keen on using ext-plugin.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号