Map-backed ActionForm


有的時候您的表單內容可能是由程式動態產生的,這時候表單上的欄位與參數事先並無法得知,因而無法事先決定好 ActionForm 的屬性,在Struts 1.1中,您可以使用Map-backed ActionForm,這樣的ActionForm使用Map來儲存表單的欄位值,一個例子如下:
  • UserForm.java
package onlyfun.caterpillar;

import java.util.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class UserForm extends ActionForm {
protected Map map = new HashMap();

public void setValue(String key, Object value) {
map.put(key, value);
}

public Object getValue(String key) {
return map.get(key);
}

public Map getMap() {
return map;
}

public void reset(ActionMapping mapping,
HttpServletRequest req) {
map.clear();
}
}

在Action類別中,您可以如下面的方式來取值:
  • LoginAction.java
package onlyfun.caterpillar;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
UserForm userForm = (UserForm) form;

String name =
(String) userForm.getValue("name");
String password =
(String) userForm.getValue("password");
.....
}
}