Struts防止表单重复提交

来源:互联网 发布:fx5u有什么编程软件 编辑:程序博客网 时间:2024/04/30 14:11

当add.jsp 成功以后,调用list方法后,显示刚才添加的数据,但是此时再次回车又将添加一条数据,这就是表单重复提交。

解决方法:

1、可以在add方法成功后,不要调用list();,而是返回一个字符串:"addSuccess",在Struts中配置,见一下代码

public class StrutsAction extends ActionSupport implements ModelDriven<Employee>{private IEmployeeService service =new EmployeeService();private Employee employee = new Employee();public Employee getEmployee() {return employee;}public void setEmployee(Employee employee) {this.employee = employee;}@Overridepublic Employee getModel() {// TODO Auto-generated method stubreturn employee;}//添加数据public String add() {try {service.add(employee);return list();//此处return "addSuccess";} catch (Exception e) {throw new RuntimeException(e);}}//更新数据public String viewupdate() {try {System.out.println(employee.getId());int id =  employee.getId();Employee em = service.getEmployeeById(id);ActionContext.getContext().getValueStack().pop();ActionContext.getContext().getValueStack().push(em);return "viewupdate";} catch (Exception e) {throw new RuntimeException(e);}}public String update() {try {service.update(employee);return list();} catch (Exception e) {throw new RuntimeException(e);}}//数据列表public String list() {List<Employee> list =  service.getAllList();ActionContext.getContext().getContextMap().put("employeeList", list);return "list";}}
然后在Struts中配置:

<struts><package name="strutsgfg" extends="struts-default"><action name="struts_*" class="com.gta.action.StrutsAction" method="{1}"><result name="list">/listEmployee.jsp</result> <result name="viewupdate">/updateEmployee.jsp</result>                                                <result name="addSuccess" type="redirectAction">/struts_list</result>                 </action></package></struts>
方法2:使用拦截器进行拦截

上面的直接返回 list();

add.jsp中添加:

<body>      <s:form action="struts_add" method="post">    <s:token></s:token>//第1步:添加这句话    姓名:<s:textfield name="userName"></s:textfield>    编号:<s:textfield name="id"></s:textfield>    <s:submit value="保存"></s:submit>    </s:form>  </body>
<struts><package name="strutsgfg" extends="struts-default"><action name="struts_*" class="com.gta.action.StrutsAction" method="{1}">                        第二步:设置拦截器                        <!-- 防止表单重复提交,第二步: 配置" 防止表单重复提交拦截器" --><interceptor-ref name="defaultStack"></interceptor-ref><interceptor-ref name="token"><!-- 指定拦截哪些方法需要防止表单重复提交(add) --><param name="includeMethods">add</param></interceptor-ref><!-- 防止表单重复提交,第三步: 如果用户重复提交了跳转到指定的错误页面  --><result name="invalid.token" type="redirectAction">struts_list</result><result name="list">/listEmployee.jsp</result> <result name="viewupdate">/updateEmployee.jsp</result></action></package></struts>



原创粉丝点击