ectedMountains 的 String[] 数组,并使它可以用于页面:
清单 3. 表单的 Action
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* A simple Action for Checkbox test.
*
* @author Danilo Gurovich
*/
public final class CheckboxTestAction
extends Action {
// -------------------------- OTHER METHODS --------------------------
/**
* The execute method
*
* @param mapping ActionMapping
* @param form CheckboxTestForm
* @param request HttpServletRequest
* @param response HttpServletRespons
* @return success to the confirmation page
* @throws ServletException not thrown, but could be!
* @throws Exception ditto.
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, Exception {
// Extract attributes needed
String[] selectedMountains =
((CheckboxTestForm) form).getSelectedMountains()
;
System.out.println("htmlString RETURNED*\n" +
selectedMountains.toString());
//Save the htmlString in the session for later...
HttpSession session = request.getSession();
session.setAttribute(CheckboxConstants.MOUNTAINS, selectedMountains);
return (mapping.findForward("success"));
}
}
Struts的动态复选框-用动态选择的元素轻松创建复选框(5)
时间:2011-08-18 IBM Danilo Gurovich
扩充 Himalayas
有了这个代码,工作就完成了,差不多可以展示成果了!用户现在可以提交 JSP 表单并在 Action 类 引用的对应页面中查看结果。清单 4 中的代码段显示了用户在简单 JSP 页面的表单中选中的复选框列表 :
清单 4. 复选框选择的结果
<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic"%>
<%-- html code, etc... -->
<logic:iterate id="mountain" property="mountains" name="testForm">
<bean:write name="mountain"/><br/>
</logic:iterate>
<hr size=5 color="black"/>
<%-- some more html code, etc... -->
这个诀窍的工作方式
这个诀窍的关键是表单 bean 中的字段被传递到页面。查看相关 JSP 代码有助于澄清这点。一旦表单 bean 被实例化:
<html:form action="/FormAction"
name="testForm"
type=" com.strutsrecipes.CheckboxTestForm">
下一步为 Java 类的 mountains 变量中的每个 mountain 创建一个复选框。要做到这一点,我必须像 下面这样在 String[] 数组中迭代:
<logic:iterate id="mountain" property="mountains"
name="testForm">
使用 <logic:iterate> 标记,我调用了 testForm bean 中的 getMountains() 方法。它在 |