I am trying to use a HashMap to create a grid in JSP using Struts2. I am able to load the page with the values I populate in the HashMap, but when I submit it, the HashMap doesn't get back to the action method (I get a NullPointerException trying to access the HashMap). Can someone tell me what I am doing wrong? Is what I am doing in the JSP correct?
My Action Method (Load and Submit) :-
public class HashMapGridAction extends ActionSupport{
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(HashMapGridAction.class);
private HashMap<String, TestObject> hashMap;
public String load() {
this.hashMap = new HashMap<String, TestObject>();
TestObject testObject1 = new TestObject();
testObject1.setCode("A");
testObject1.setDescription("Alphabet A");
this.hashMap.put("A", testObject1);
TestObject testObject2 = new TestObject();
testObject2.setCode("B");
testObject2.setDescription("Alphabet B");
this.hashMap.put("B", testObject2);
TestObject testObject3 = new TestObject();
testObject3.setCode("C");
testObject3.setDescription("Alphabet C");
this.hashMap.put("C", testObject3);
return SUCCESS;
}
public String submit() {
//This is where I get the NullPointerException
Iterator<String> iter = this.hashMap.keySet().iterator();
while (iter.hasNext()){
String key = iter.next();
logger.debug("Key : " + key);
logger.debug("Code: " + this.hashMap.get(key).getCode());
logger.debug("Description: " + this.hashMap.get(key).getDescription());
}
return SUCCESS;
}
public HashMap<String, TestObject> getHashMap() {
return hashMap;
}
public void setHashMap(HashMap<String, TestObject> hashMap) {
this.hashMap = hashMap;
}
}
The value object on the HashMap (TestObject) :-
public class TestObject {
private String code;
private String description;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
JSP :-
<s:form action="hashMapGridSubmit">
<table>
<s:iterator value="hashMap" var="testObject">
<tr>
<s:hidden name="hashMap[%{key}].code" value="%{value.code}"></s:hidden>
<td><s:property value="%{value.code}" /></td>
<td><s:textfield theme="simple"
name="hashMap[%{key}].description" value="%{value.description}" /></td>
</tr>
</s:iterator>
</table>
<s:submit theme="simple" value="Submit" />
</s:form>
Struts.xml :-
<action name="hashMapGridLoad" class="com.dowill.struts2.hashmap.HashMapGridAction" method="load">
<result name="success">/hashmap/hashmapgrid.jsp</result>
</action>
<action name="hashMapGridSubmit" class="com.dowill.struts2.hashmap.HashMapGridAction" method="submit">
<result name="success">/hashmap/hashmapgrid.jsp</result>
</action>
Thank you !!