Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid multiple form submission

Tags:

jsf-2

In JSF2, is there any way to handle the multiple form submit (user clicks submit button multiple times)? Now we are getting the below exception in server

java.lang.IllegalStateException: Response already committed
java.lang.IllegalStateException: Response already committed
javax.faces.FacesException: socket write error: Connection aborted by peer
like image 799
user684434 Avatar asked Feb 06 '12 16:02

user684434


1 Answers

That depends on how you're submitting the form. If you're using <f:ajax> or any other Ajax based tag to perform the submit by Ajax, then your best bet is to use jsf.ajax.addOnEvent() to add a function which disables the button when the Ajax request is about to be sent and re-enables it after the Ajax response is retrieved.

E.g. as follows, which you include after the JSF Ajax scripts are included, e.g. inside a <script> or <h:outputScript> referring a .js file in <h:head>.

jsf.ajax.addOnEvent(function(data) {
    if (data.source.type != "submit") {
        return; // Ignore anything else than input type="submit".
    }

    switch (data.status) {
        case "begin":
            data.source.disabled = true; // Disable input type="submit".
            break;
        case "complete":
            data.source.disabled = false; // Re-enable input type="submit".
            break;
    }    
});

If you're not using Ajax to perform the submit, then one of the ways is to throw in a setTimeout() function in onclick which disables the button a few ms after click.

Basically,

<h:commandButton 
    id="foo"
    value="submit"
    action="#{bean.submit}"
    onclick="setTimeout('document.getElementById(\'' + this.id + '\').disabled=true;', 50);"
/>

The setTimeout() is mandatory, because when you disable it immediately, then the name=value pair of the button won't be sent along with the request which would cause JSF to be unable to identify the action to be executed. You can of course refactor it to some DOM ready or window onload function which applies this for all submit buttons (jQuery would be tremendously helpful in this).

like image 196
BalusC Avatar answered Dec 07 '22 22:12

BalusC