且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ajax调用中保持参数?

更新时间:2023-01-13 17:40:19

将其注册为<f:viewParam>

<f:viewParam name="foo" value="#{mybean.bar}" />

,而不使用<h:form>,请使用 OmniFaces (在幕后使用了自定义ViewHandler实现,该实现会自动收集所有视图参数并将它们附加到getActionURL()的结果中用作表单操作网址的方法):

<o:form includeViewParams="true">
    ...
</o:form>

这样,所有视图参数都包含在表单的操作URL中,因此将以通常的方式作为请求参数结束,而无需摆弄<f:param>并且在<p:ajax>(和<f:ajax>)中毫无头绪. /p>

Whenever I make an ajax call, my URL param expires. The workaround I have done is to pass a param request inside every button like in:

<p:commandLink value="Submit" actionListener="#{mybean.dosomething}">
   <f:param name="foo" value="#{mybean.bar}"/>
</p:commandLink>

However, in some scenarios I can't do the above workaround. For example when I'm using primefaces rowEditEvent:

<p:ajax event="rowEditCancel" listener="#{mybean.onCancel}"/>

The param expires when I make this ajax call and results in error before invoking #{mybean.onCance} as I'm reading datatable's data from the param in URL.

So how can I maintain the param value when I make such an ajax call?

PS: mybean is ViewScoped

Problem Extension:

The <o:form> has solved part of the problem, but now I can't send params inside the form for dynamic image streaming inside the table. See the following:

<p:dataTable value="#{mybean.data}" var="var">
    <p:column headerText="Thumbnail">
        <p:graphicImage value="#{streamer.thumbnail}">
            <f:param name="id" value="#{var.id}"/>
        </p:graphicImage>
    </p:column>
</p:dataTable>

Streamer Bean (RequestScoped):

 public StreamedContent getThumbnail() throws IOException {
      FacesContext context = FacesContext.getCurrentInstance();
      if (context.getRenderResponse()) {
          return new DefaultStreamedContent();
      }
      else {
         String string = context.getExternalContext().getRequestParameterMap().get("id");
        Long id = Long.parseLong(idString);
        MyImage img = (MyImage) service.find(MyImage.class, id);//get resource
        StreamedContent sc = new DefaultStreamedContent(img.getInputStream(), "image/jpg", img.getName());
        return sc;
        }
 }

Here string is always null and parameter is not passed resulting in error

Register it as a <f:viewParam>

<f:viewParam name="foo" value="#{mybean.bar}" />

and instead of <h:form>, use OmniFaces <o:form> with includeViewParams="true" (which uses under the covers a custom ViewHandler implementation which automatically collects all view parameters and appends them to the outcome of the getActionURL() method which is used as form action URL):

<o:form includeViewParams="true">
    ...
</o:form>

This way all view params are included in the form's action URL and will therefore end up as request parameters the usual way without the need to fiddle with <f:param> and being clueless inside <p:ajax> (and <f:ajax>).