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;
}
}
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:
Get map from request :
#set ($categoryMap= $request.get('attributes').get('categoryMap'))
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
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.
精彩评论