j2ee之struts2表单细节处理

/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>
原文地址:https://www.cnblogs.com/ShaoXin/p/7068952.html