user684434
user684434

Reputation: 1165

Avoid multiple form submission

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

Upvotes: 6

Views: 5758

Answers (2)

user1193816
user1193816

Reputation: 1

You can add a disabled button on the page which does nothing and show it when the submit button is clicked.

<div id="disabled" style="display:none;">
     <span class="disabled-button"/>
</div>
<div id="enabled" style="display:block;">
     <span class="enabled-button">
          <h:commandLink id="submit"/>
     </span>
</div>


$('#submit').live("click", function() {
$('#enabled').hide();
$('#disabled').show();
});

Upvotes: 0

BalusC
BalusC

Reputation: 1108577

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).

Upvotes: 4

Related Questions