Menu Home

Struts DynaActionForm 动态表单简介

Struts DynaActionForm 动态ActionForm出现的主要功能是为了防止ActionForm的膨胀,全部代码由Struts自动生成,不用手工写多个ActionForm.
DynaActionForm 动态ActionForm 与普通ActionForm 并没有太大的区别。动态ActionForm 避免了书写ActionForm,但配置变得更复杂了。而普通ActionForm 使解析请求参数变得更直观。

  • 编写表单
  • <%@ page language="java" pageEncoding="gb2312"%>
    <form action="login.do" method="post">
    	username:<input type="text" name="username" /><br/>
    	userpass:<input type="text" name="userpass" /><br/>
    	<input type="submit" value="login" />
    </form>
  • 配置 struts-config.xml 中 form-bean
  • <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
    
    <struts-config>
      <data-sources />
      <!-- 配置动态表单BEAN -->
      <form-beans>
      	<form-bean name="loginForm" type="org.apache.struts.action.DynaActionForm">
      		<form-property name="username" type="java.lang.String" />
      		<form-property name="userpass" type="java.lang.String" />
      	</form-bean>
      </form-beans>
      <!-- 结束配置 -->
      <global-exceptions />
      <global-forwards />
      <action-mappings >
        <action
          attribute="loginForm"
          name="loginForm"
          path="/login"
          scope="request"
          type="cn.net.royakon.action.LoginAction">
          <forward name="ok" path="/ok.jsp" />
          <forward name="fail" path="/index.jsp" />
        </action>
    
      </action-mappings>
    
      <message-resources parameter="cn.net.royakon.ApplicationResources" />
    </struts-config>
  • 在Action中使用表单bean
  • public ActionForward execute(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response) {
    		DynaActionForm loginForm = (DynaActionForm) form;
    		// 通过 loginForm 取得已配置的动态表单Bean的值
    		String username = loginForm.getString("username");
    		String userpass = loginForm.getString("userpass");
    		if (username.equals(userpass)) {
    			request.setAttribute("result","ok");
    			return mapping.findForward("ok");
    		}
    		return mapping.findForward("fail");
    	}

DynaActionForm 到底好不好用,仁者见仁,智者见智,虽然提高了代码的自动生成能力,但是又带来了复杂性方面的代价。如何取舍就看你了!我个人不是很喜欢这个功能。

Categories: 网页编程

Tagged as:

RoyAkon