Alpesh Jikadra
Alpesh Jikadra

Reputation: 1722

Submit java.util.Map from Jsp to Struts 1 Action class

I am using Struts 1,

I want to submit data from my JSP page to Struts 1 Action Class using,

Field in FormBean is something like below

Map<String, Map<String,List<Object>>> data = new HashMap<String, Map<String,List<Object>>>();

Does any one know how to achieve this?

Upvotes: 1

Views: 1747

Answers (1)

Turan Y&#252;ksel
Turan Y&#252;ksel

Reputation: 131

In order to keep the talk short, I'm giving a solution for a Map<String,List<MyBean>>. With little effort, one can extend the following to be the answer to the question:

Struts 1.x requires you to create all objects in ActionForm.reset() before it populates primitive values. If your form has an object with children, those children must be assigned proper values, i.e. if you have <html:text property="parent.child" /> then you must do parent.setChild(new Child()) in your reset().

Similarly, if you have a list-based form element, then every referenced index of the form element have to be initialised, i.e. <html:text property="myBeanList[12].beanMember"/> requires something equivalent to myBeanList.add(12, new MyBean()) in the reset() method. Maps also have a similar requirement; <html:text property="myBeanMap('key').beanMember"/> requires myBeanMap.put('key',new MyBean()).

With the help of some extra hidden form fields or -better- a parser to detect indexes that are needed, you can detect the index positions at which you have to create new objects.

If we go the easy way and send required index information with HTTP GET/POST parameters, we map keys reside in mapKeys, e.g.

<input type="hidden" name="mapKeys" value="key1,key2,key3"/>

and the lengths of lists at each key position reside in variables like key1_length:

<input type="hidden" name="key1_length" value="10"/>

In this case, the reset() method would be something like this:

public void reset(ActionMapping mapping, HttpServletRequest request) {
   this.data = new HashMap<String,List<MyBean>>();
   String requiredKeys=request.getParameter("mapKeys");
   for (String key: requiredKeys.split(",")) {
     List<MyBean> lst = new ArrayList<MyBean>();
     int listLength = Integer.parseInt(request.getParameter(key+"_length"));
     for (int i = 0; i < listLength; i++)
        lst.add(new MyBean());
     this.data.put(key, lst);
   }

}

so that it can get

<html:text property="data('key1')[3].beanMember"/>

when the form is populated. In case the index information is not consistent with the other form elements, you might run into exceptions regarding BeanUtils.setProperty().

Btw, all I told is ok to get data from an HTML form which is not multipart/form-data, so no lists and file uploads together.

Upvotes: 1

Related Questions