1. 程式人生 > >j2ee之struts2表單細節處理

j2ee之struts2表單細節處理

serial method blog submit sym this 同時 pac onu

/struts-tags中自帶了很多標簽

比如一個簡單的登錄表單,其中自帶了很多的樣式,實際上如果你不需要用到struts的實際功能的時候不建議使用

     <s:form   action="user_save">
          <s:token></s:token>
              <s:textfield name="username" label="用戶名"></s:textfield>
              <s:textfield name="pwd" label="密碼"></s:textfield
> <s:submit value="提交"></s:submit> </s:form>

你可以通過設置屬性 theme="simple"來取消他自帶的樣式

其次是ModelDriven,意思是直接把實體類當成頁面數據的收集對象。在Action實現ModelDriven接口,可以很方便的對實體類對象的屬性賦值,不過在Action中實體類對象要new出來並且重寫ModelDriven的getModel方法,返回值是你的實體類對象代碼如下:

package com.xinzhi.action;

import java.util.List;

import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; import com.xinzhi.dao.impl.UserDaoImpl; import com.xinzhi.entity.UserEntity; public class UserAction extends ActionSupport implements
ModelDriven<UserEntity> { private static final long serialVersionUID = 1L; private UserEntity userEntity = new UserEntity(); UserDaoImpl userDaoImpl = new UserDaoImpl(); public UserEntity getUserEntity() { return userEntity; } public void setUserEntity(UserEntity userEntity) { this.userEntity = userEntity; } public UserEntity getModel() { return userEntity; } }

然後是表單的數據回顯,在Action當中把你的實體類對象壓入(ValueStack)堆棧中,然後在頁面中取出堆棧你要的值,方法如下

  public String view() {
        UserEntity selectAUserEntity = userDaoImpl.selectAUserEntity(userEntity
                .getId());
        ValueStack valueStack = ActionContext.getContext().getValueStack();
        valueStack.pop();
        valueStack.push(selectAUserEntity);
        return "view";
    }

最後是防止表單重復提交的方法token,我對他的理解是,在表單中如果有<token>標簽的時候,提交表單的同時在表單頁和action中隨機生成一個相同的ID值,當第一次提交過來的表單被接收時這個ID將被刪除,當被重復提交時就會找不到對應的ID值導致無法重復提交,並且發出無效指令的錯誤代碼如下

表單代碼

      <s:form   action="user_save">
            <s:token></s:token>
              <s:textfield name="username" label="用戶名"></s:textfield>
              <s:textfield name="pwd" label="密碼"></s:textfield>
              <s:submit value="提交"></s:submit>
          </s:form>

然後要在struts.xml配置文件中使用對應的攔截器,並指出重復提交時,無效的指令將會跳轉到哪一個頁面代碼如下:

     <action name="user_*" class="com.xinzhi.action.UserAction" method="{1}">
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <interceptor-ref name="token">
                <param name="includeMethods">save</param>
            </interceptor-ref>
        </action>

j2ee之struts2表單細節處理