如何通过JavaScript调用带有参数的托管bean方法

时间:2013-09-24 07:44:52

标签: javascript jsf primefaces httprequest

我正在开发一个Web应用程序,我使用JSF和PrimeFaces框架以及外部Geo Map API。

当我在地图上点击POI时,Map API会给我POI_id。但这对我来说还不够,我想从servlet获取有关POI的信息并在弹出窗口中显示它。 (地址,姓名,电话号码等字段)。

所以,当我点击地图上的POI时,我需要向托管bean中的servlet发送HTTP请求。

我可以获得poi_id,但我无法将此ID发送到后端托管bean,因此无法获取POI信息。

如何将poi_id发送到托管bean并处理响应以显示在弹出窗口中?

2 个答案:

答案 0 :(得分:20)

您可以使用PrimeFaces remote command component<p:remoteCommand>)。

  

RemoteCommand可以执行支持bean方法并执行部分操作   由自定义客户端脚本触发的更新。

以下列方式将其添加到视图中:

<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}"/>

并在Javascript中使用它:

<script type="text/javascript">
   myRemote(); //makes a remote call
</script>

或从事件处理程序中调用它:

<div onclick="myremote();">...</div>

如果您还想将参数传递给服务器,请拨打以下电话:

<script type="text/javascript">
   myRemote([{name:'param1', value:150}, {name:'param2', value:220}]); //makes a remote call with parameters
</script>

听众可能像:

public void listen(){
    FacesContext context = FacesContext.getCurrentInstance();
    Map<String,String> params = context.getExternalContext().getRequestParameterMap();
    System.out.println(params.get("param1"));
    System.out.println(params.get("param2"));
}

其中一条评论要求将值返回给Javascript 那么在这种情况下,您可以使用Primeface的Request Context execute()方法来执行您想要的任何JavaScript。

RequestContext.getCurrentInstance().execute("your javascript code");

答案 1 :(得分:11)

只需添加Kishor(中途)答案,您需要在视图中设置一个待更新的组件(在您调用它时弹出窗口),并在请求成功完成后更新它。

您可以使用远程命令发送附加了额外参数的AJAX请求,并使用jj-update更新负责弹出窗口的JSF组件。像这样(对于PrimeFaces 3.x):

<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}" 
                 update="dialog" oncomplete="dlg.show()" />
...
<div onclick="myremote([{name:'poi_id', value:poi_id}]);">...</div>
...
<p:dialog id="dialog" widgetVar="dlg">
    <h:outputText value="#{myBean.address}" />
    ...(display other information)
</p:dialog>

String address;
public void listen(){
    String poi_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("poi_id");
    address = getAddress(poi_id);
}

使用远程命令的替代方法是使用隐藏的表单,其中包含一个隐藏的输入,用于将参数传输到辅助bean,可以将其与其他bean分开,以处理基于您的必要信息的检索poi_id

<h:form id="poi-form" styleClass="invisible">
    <h:inputHidden id="poi" value="#{poiBean.poi}" />
    <p:commandButton id="info" action="#{poiBean.info}"
                     update="dialog" oncomplete="dlg.show()" />
</h:form>
<div onclick="document.getElementById('poi-form:poi').value = poi_id; 
              document.getElementById('poi-form:info').click();">...</div>
...
<p:dialog id="dialog" widgetVar="dlg">
    <h:outputText value="#{poiBean.address}" />
    ...(display other information)
</p:dialog>

@ManagedBean
@RequestScoped
public class PoiBean {

    private String poi;//getter+setter
    private String address;//getter
    //other properties

    public void listen(){
        address = getAddress(poi);
        //other properties
    }

}