JSF no redirect request after file input ajax

巧了我就是萌 提交于 2019-12-22 14:16:04

问题


I have a form in JSF 2.2:

<h:form enctype="multipart/form-data">
    <h:outputLabel>title *</h:outputLabel>
    <h:inputText value="#{bean.title}" required="" />

    <h:outputLabel>Image *</h:outputLabel>
    <h:inputFile value="#{bean.picutreFile}" a:accept="image/*">
        <f:ajax listener="#{bean.uploadPicture}" />
    </h:inputFile>

    <h:commandLink action="#{bean.save}">
        Save
    </h:commandLink>
</h:form>

The functions:

public String save() {
    return "/index?faces-redirect=true";
}

public void uploadPicture() {
    // Do nothing
}

But after I choose an image and get the call of uploadPicture function, the save function can't redirect the page. It calls to save but the redirect is not working, and just refresh the current page.

If I skip the file upload, it redirects normally. How can I make it to work?

EDIT
I have noticed that if I remove the ajax <f:ajax listener="#{bean.uploadPicture}" /> it works as expected. But I must to have that ajax because I want to display the image after upload.

EDIT 2
I can see that after the ajax called, the JSF creates a weird iframe at the bottom of the page with partial-response tag in it's body, and when I press 'Save` that iframe is redirects to the destination. Why is that??


回答1:


I reproduced it. I do agree that the behavior is confusing and unintuitive, but I wouldn't say this is a bug in the JSF implementation, because you're essentially mixing ajax with regular requests which is wrong in first place. See also this related question httpError: The Http Transport returned a 0 status code.

The correct approach is either to make the command link an ajax link as well,

<h:commandLink action="#{bean.save}">
    Save
    <f:ajax execute="@form" />
</h:commandLink>

or to remove <f:ajax> from the <h:inputFile> (and perform upload processing in save()).

<h:inputFile value="#{bean.picutreFile}" a:accept="image/*" />

That iframe you're seeing is by the way the age-old trick to simulate asynchronous behavior during file uploads, invented long before XHR2 / FormData API was standardized. This approach was during JSF 2.2 development preferred over XHR2 due to better backwards compatibility in webbrowsers (particularly MSIE). See also a.o. How to make Asynchronous(AJAX) File Upload using iframe?




回答2:


As I know JSF blocks your request till ajax call for security. Maybe you can put a processing bar or something like that while ajax calling. So user can not click save button until ajax call finish.

Can you wait a little bit after clicking upload button then click save button? It should work If i am right.



来源:https://stackoverflow.com/questions/36623750/jsf-no-redirect-request-after-file-input-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!