Struts2防止重复提交
一般使用<interceptor-ref name="token"></interceptor-ref>或者<interceptor-ref name="tokenSession"></interceptor-ref>拦截器进行处理。我们举个简单的例子:
Jsp页面:
1 <body> 2 <s:actionerror/> 3 <s:form action="student" method="post" > 4 <s:token></s:token> 5 姓名:<input type="text" name="student.name"></input> 6 年龄:<input type="text" name="student.age"></input> 7 <s:submit value="添加"></s:submit> 8 </s:form> 9 </body>
model:
1 public class Student { 2 private String name; 3 private int age; 4 public String getName() { 5 return name; 6 } 7 public void setName(String name) { 8 this.name = name; 9 } 10 public int getAge() { 11 return age; 12 } 13 public void setAge(int age) { 14 this.age = age; 15 } 16 @Override 17 public String toString() { 18 return "Student [name=" + name + ", age=" + age + "]"; 19 } 20 }
StudentAction处理:
1 public class StudentAction extends ActionSupport{ 2 private static final long serialVersionUID = 1L; 3 private Student student; 4 public Student getStudent() { 5 return student; 6 } 7 public void setStudent(Student student) { 8 this.student = student; 9 } 10 public String add()throws Exception{ 11 System.out.println("正在添加学生: "+student); 12 Thread.sleep(5000); 13 System.out.println(student.getName()+"添加成功!"); 14 return SUCCESS; 15 } 16 }
配置struts.xml:
1 <struts> 2 <package name="manager" extends="struts-default"> 3 <action name="student" class="com.java1234.action.StudentAction" method="add"> 4 <result name="success">/success.jsp</result> 5 <!-- <result name="invalid.token">/student.jsp</result> 6 <interceptor-ref name="token"></interceptor-ref> 7 <interceptor-ref name="defaultStack"></interceptor-ref> 8 //方法1 9 --> 10 <interceptor-ref name="tokenSession"></interceptor-ref> 11 <interceptor-ref name="defaultStack"></interceptor-ref> 12 //方法2 13 </action> 14 </package> 15 </struts>
Success.jsp:
1 <body>学生添加成功!</body>
效果:
在添加了延迟之后,多次点击提交,我们发现只会添加一次。防止重复提交成功!