龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

Struts的动态表单的应用

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
Struts的动态表单的应用 假如你使用过struts先前的版本,你就会注重到你需要花费大量的时候来写ActionForm类文件,而这些类文件对于struts都是非常要害的(它充当“View”的一部分),通

  Struts的动态表单的应用
  
   假如你使用过struts先前的版本,你就会注重到你需要花费大量的时候来写ActionForm类文件,而这些类文件对于struts都是非常要害的(它充当“View”的一部分),通常它的结构就是bean properties在加上一个validate方法(有时还有reset方法)。
  
   随着struts1.1版本的推出,开发员有了另外一种方法来完成前面的任务:使用DynaBeans。DynaBeans动态生成Java Beans。这就意味着我们可以通过配置(通常利用XML)
  
   来生成formbean而不是在formbean中硬编码。
  
   为了了解DynaBeans(struts中为Dynaforms)是如何工做的,让我们看一个简单的表单,字段有:name,address,telephone等,下面的代码为通常的写法(没有使用Dynaforms)。
  
   article1.CustomerForm
  
   package article1;
  
   import org.apache.struts.action.ActionForm;
   import org.apache.struts.action.ActionErrors;
   import org.apache.struts.action.ActionMapping;
   import org.apache.struts.action.ActionError;
   import javax.servlet.http.HttpServletRequest;
  
   public class CustomerForm extends ActionForm {
  
   protected boolean nullOrBlank (String str) {
   return ((str == null) (str.length() == 0));
   }
   public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
   ActionErrors errors = new ActionErrors();
   if (nullOrBlank(lastName)) {
   errors.add("lastName",
   new ActionError("article1.lastName.missing"));
   }
   if (nullOrBlank(firstName)) {
   errors.add("firstName",
   new ActionError("article1.firstName.missing"));
   }
   if (nullOrBlank(street)) {
   errors.add("street",
   new ActionError("article1.street.missing"));
   }
   if (nullOrBlank(city)) {
   errors.add("city",
   new ActionError("article1.city.missing"));
   }
   if (nullOrBlank(state)) {
   errors.add("state",
   new ActionError("article1.state.missing"));
   }
   if (nullOrBlank(postalCode)) {
   errors.add("postalCode",
   new ActionError("article1.postalCode.missing"));
   }
   if (nullOrBlank(phone)) {
   errors.add("phone",
   new ActionError("article1.phone.missing"));
   }
   return errors;
   }
  
   private String lastName;
   private String firstName;
   private String street;
   private String city;
   private String state;
   private String postalCode;
   private String phone;
  
   public String getLastName() {
   return lastName;
   }
  
   public void setLastName(String lastName) {
   this.lastName = lastName;
   }
  
   public String getFirstName() {
   return firstName;
   }
  
   public void setFirstName(String firstName) {
  
  
精彩图集

赞助商链接