欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

J2EE中的struts2表单细节处理

时间:2021-05-31 08:25:14|栏目:JAVA代码|点击:

/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>

上一篇:详谈Jedis连接池的使用

栏    目:JAVA代码

下一篇:javassist使用指南

本文标题:J2EE中的struts2表单细节处理

本文地址:http://www.codeinn.net/misctech/132407.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有