p:commandLink не может открыть страницу в новом окне / вкладке

Я пытаюсь создать ссылку, чтобы открыть новую страницу в другом окне / вкладке и показать некоторые сообщения из бина, но не могу этого сделать, интересно, знаете почему?

вот мой файл xhtml:

<html:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui"
  xmlns:c="http://java.sun.com/jsp/jstl/core"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:body>
    <h:form id="form66">
    <p:commandLink actionListener="#{testing.getMessage}" action="msg.xhtml" target="_blank">get Msg</p:commandLink>
    </h:form>
  </h:body>
</html>

вот моя страница Msg.xhtml

<HTML xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui"
  xmlns:ui="http://java.sun.com/jsf/facelets">
  <h:head>
    <title>testing</title>
  </h:head>
  <h:body>
    <div class="div">
      <p:panel>
        <f:facet name="header">
          testing
        </f:facet>
        <div class="paddingForPanel">
          <h:outputText value="#{testing.msg}" escape="false"/>             
        </div>
      </p:panel>            
    </div>
  </h:body>
</HTML>

вот мое тестирование

public void getMessage() {      
    this.msg = "haha";
}

private String msg;
public String getMsg() {
    return msg;
}
public void setMsg(String msg) {
    this.msg = msg;
}


вышеприведенный код не может открыть новую вкладку / окно, я пытаюсь сделать, как показано ниже, успешно открыть новую страницу в новой вкладке, но сообщение пустое, когда я отлаживаюсь, получилось успешно, вызов слушателя getMessage, интересно почему сообщение msg пусто на странице msg.xhtml? Заранее спасибо....

<p:commandLink actionListener="#{testing.getMessage}" oncomplete="window.open('msg.xhtml')">broadcast Msg</p:commandLink>

8 ответов

<p:commandLink> есть некоторые проблемы с AJAX, используйте <h:commandLink> вместо.

 <h:commandLink actionListener="#{testing.printMessage}" action="/Msg.html" target="_blank">get Msg</h:commandLink>

изменено <p:commandLink> в <h:commandLink> и ваш код работает нормально.

Оба не работают, поэтому проблема не в ajax. Проблема в целевом атрибуте p:commandLink не работает...

<p:commandLink value="New Window" ajax="false" target="_blank" action="test"/>

<p:commandLink value="New Window" target="_blank" action="test"/>

ТАК мы должны использовать

<h:commandLink value="New Window" target="_blank" action="test"/>

Я делаю это так:

<p:commandLink id="link" actionListener="#{testing.getMessage}" 
    oncomplete="popupwindow('msg.xhtml', 'newwindow');" >  
    <h:outputText value="broadcast Msg" />
</p:commandLink>

С некоторыми JavaScript:

<script type="text/javascript">    
function popupwindow(url, title) {      
    window.open(url , title, "toolbar=no, scrollbars=yes, resizable=yes, top=170, left=170, width=800, height=600");        
}    
</script>

В этом примере вы открываете новое окно, надеюсь, это поможет!

Если вы используете remotecommand, то вы можете сделать так

<p:remoteCommand name="lookAndBookNewTab"
     process="@this" action="#{lookAndBookMB.onPageLoadForNewTab()}"
     rendered="#currentUserManager.
     hasPermission('LookAndBook','View')}"             update=":messageForm:growl" />

И мой JavaScript:

<script> 
    if(event.ctrlKey &amp;&amp; event.shiftKey &amp;&amp; event.keyCode == 119) {
     lookAndBookNewTab(); 
    event.preventDefault();
</script>

Метод действия ServerSide:

public String onPageLoadForNewTab(){
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); String url = req.getRequestURL().toString();
        url=(url.substring(0, url.length() - req.getRequestURI().length()) + req.getContextPath() + "/"); url=url+navigationpagename+".jsf"; RequestContext.getCurrentInstance().
        execute("window.open('"+url+"','_blank')");** 
    return ""; }

Попробуйте это в коде вашего контроллера, он отлично сработал для меня.

HttpServletResponse res = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            String uri = req.getRequestURI();
            res.getWriter().println("<script>window.open('" + myUrl + "','_blank', 'location=yes,height=600,width=800,scrollbars=yes,status=yes'); window.parent.location.href= '"+uri+"';</script>");
            FacesContext.getCurrentInstance().responseComplete();   

Если кому-то интересно, используя Primefaces 9,10,11, сделайте это

      <p:commandLink value="New Window" ajax="false" target="_blank" action="test"/>

работает, если вы не хотите использовать h:commandLink

Как это,

<h:link target="_blank" value="Other page" outcome="your url"></h:link>

Удачи!

Как это

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
     'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

     <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">


    <h:head>
        <h:outputStylesheet library="base" name='jquery-ui-1.8.16.custom.css' />
    </h:head>
    <span style="background-color: rgb(192, 192, 192);">
      <h:form target="_blank">
        <p:commandButton value="Run" action="#{bean.createReport}"  />
      </h:form>
    </span>
    </html>

смотрите: введите описание ссылки здесь

Другие вопросы по тегам