温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

J2EE中的struts2表单细节处理

发布时间:2020-10-16 20:08:15 来源:脚本之家 阅读:123 作者:情似雨餘黏地絮 栏目:编程语言

/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表单细节处理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI