miercuri, 25 februarie 2015

DeltaSpike - JSF Double-Submit Prevention

The "double submit" notion describes a sequence of two or more submits. Excepting the intention, this scenario commonly appear in the following three cases:
·         instead of one click, the user double-clicks the Submit button
·         there is a long task running and the user click the Submit button again (an impatient user)
·         when the button is clicked, there is no visual feedback, so the user click again

There are several workarounds to avoid this kind of issue (e.g. disable the Submit button), but in this post we are interested in DeltaSpike approach.

Well, let's take the following dummy case. First, we have a simple form with a Submit button:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
 <h:head>
  <title></title>
 </h:head>
 <h:body>  
  <h:form>                       
   <h:commandButton value="Submit" action="#{someBean.dummyLongAction()}"/>               
  </h:form>
       
  Submit number: #{someBean.submit}
 </h:body>
</html>

And a bean that simulates a long task (so we have plenty of time for a double submission):

@Named
@SessionScoped
public class SomeBean implements Serializable {

 private int submit = 0;

 public void dummyLongAction() {       
  submit++;
  for (int i = 0; i < 1000000; i++) {
       System.out.println("I'm a dummy action ! Submit: " + submit);
  }       
 }

 public int getSubmit() {
  return submit;
 }

 public void setSubmit(int submit) {
  this.submit = submit;
 }       
}

Now, I've performed a test in Google Chrome (left side - initial request, center - server side snippet output, right side - after double submission):
Obviously, the double submission "successfully" worked!

Further, I've added the DeltaSpike double-submit prevention component. So, I've added the DeltaSpike namespace, http://deltaspike.apache.org/jsf and the <ds:preventDoubleSubmit/>, like this:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ds="http://deltaspike.apache.org/jsf">
 <h:head>
  <title></title>
 </h:head>
 <h:body>  
  <h:form>                       
   <h:commandButton value="Submit" action="#{someBean.dummyLongAction()}"/>  
   <ds:preventDoubleSubmit/>
  </h:form>
       
  Submit number: #{someBean.submit}
 </h:body>
</html>

Now, I've performed a test in Google Chrome (left side - initial request, center - server side snippet output, right side - after double submission):
Great! The double submission was successfully prevented!

Complete application on GitHub.

Niciun comentariu:

Trimiteți un comentariu