p:remoteCommand returns <eval> twice in ajax response - jsf

I try to render a new page in a new window (or tab) with the link I get from a selected page object in an autoComplete component.
After trying multiple options the only chance in my opinion is to use javascript to catch the submit, trigger a remote command, that gives me a javascript call with the link attribute from the page object.
JSF-Snipplet (with reduced attributes in autoComplete)
<h:form id="autoCompleteForm">
<p:autoComplete id="autoComplete" widgetVar="autoCompleteWidget" value="#{pageBean.selectedPage}" />
<p:remoteCommand action="#{pageBean.showPage}" name="showPage" />
</h:form>
some JS:
// form submit
('#autoCompleteForm').on('submit', function(e) {
e.preventDefault();
showPage();
});
// open link
var openLink = function(pageLink) {
window.open(pageLink, '_blank');
};
Bean part for action
public void showPage() {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("openLink('" + selectedPage.getLink() + ".xhtml')");
}
Everything works nice together, but the response contains the eval tag twice.
<partial-response>
<changes>
<update id="javax.faces.ViewState"><![CDATA[2851816213645347690:-2276123702509360418]]></update>
<eval><![CDATA[openLink('target.xhtml');]]></eval>
<eval><![CDATA[openLink('target.xhtml');]]></eval>
</changes>
</partial-response>
I tried different approaches with redirects or returning view names, but that all leads to no satisfying solutions (e.g. URL not changing or no new window).

Problem solved:
I had defined PrimePartialViewContextFactoryin my faces-config before:
<factory>
<partial-view-context-factory>org.primefaces.context.PrimePartialViewContextFactory</partial-view-context-factory>
</factory>
By removing it the application acts like expected.
This also solves a problem (JSON.parse: unexpected non-whitespace character after JSON data) with pagination and sorting in DataTables.

Related

Update doesn't work when call sendRedirect (HttpServletResponse) [duplicate]

I have a button which opens a new tab with a generated pdf-file.
However, after I click on the button, I want to navigate to another page.
That means, after clicking on the button i want to open a new tab with the pdf and navigate to another page on the initial tab. I am using primefaces p:commandButton and tried with onclick="window.location.href='www.google.de'" but it does not work. However onclick="window.lalert('www.google.de')" does work.
This is my code:
<h:form id="transForm" target="_blank">
<p:commandButton value="Zertifikat erstellen" ajax="false"
label="Speichert die Anmeldung und erstellt ein Zertifikat im PDF-Format"
action="#{transportErfassen.generatePDFZertifikat()}"/>
</h:form>
generatePDFZertifikat() does create a pdf-File with following code, I think here is the issue:
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/pdf" );
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "inline; filename=\"" + fileName +"\"");
externalContext.setResponseContentLength(out.length);
externalContext.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>());
//setze explizit auf OK
externalContext.setResponseStatus(200);
OutputStream os = externalContext.getResponseOutputStream();
os.write(out, 0, out.length);
os.flush();
facesContext.responseComplete();
facesContext.renderResponse();
You're basically trying to send 2 responses back to 1 request. This is not ever going to work in HTTP. If you want to send 2 responses back, you've got to let the client fire 2 requests somehow. You were already looking in the right direction for the solution, with little help of JavaScript it's possible to fire multiple requests on a single event (click). Your attempt in onclick is however not valid, the change of window.location on click of the submit button, right before the form submit, completely aborts the original action of the button, submitting the form.
Your best bet is to directly navigate to the result page which in turn invokes JavaScript window.open() on page load, pointing to the URL of the PDF file which you'd like to open. It's namely not possible to send some HTML/JS code along with the PDF file instructing a navigation (as that would obviously corrupt the PDF file). This also means, that you can't return the PDF directly to the form submit request. The code has to be redesigned in such way that the PDF can be retrieved by a subsequent GET request. The best way is to use a simple servlet. You could store the generated PDF temporarily on disk or in session, associated with an unique key, and pass that unique key as request pathinfo or parameter to the servlet in window.open() URL.
Here's a kickoff example:
Initial form:
<h:form>
...
<p:commandButton ... action="#{bean.submit}" />
</h:form>
Bean:
public String submit() {
File file = File.createTempFile("zertifikat", ".pdf", "/path/to/pdfs");
this.filename = file.getName();
// Write content to it.
return "targetview";
}
Target view:
<h:outputScript rendered="#{not empty bean.filename}">
window.open('#{request.contextPath}/pdfservlet/#{bean.filename}');
</h:outputScript>
PDF servlet (nullchecks etc omitted for brevity; Java 7 assumed for Files#copy()):
#WebServlet("/pdfservlet/*")
public class PdfServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File("/path/to/pdfs", request.getPathInfo().substring(1));
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"zertifikat.pdf\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
As BalusC said, Refresh/navigate current page and opening downloading file are two different responses, there must be two resquests. I encountered a similar problem. I solved it with jsf ajax successfully.
Here's part of my code:
XHTML:
<h:commandButton id="download-button" class="download-button"
value="download">
<f:ajax event="click" execute="#form" render=":msg-area"
listener="#{myController.checkForDownload}" onevent="checkCallBack" />
</h:commandButton>
<h:commandButton id="download-button2" class="download-button2"
value="download" style="display: none;"
action="#{myController.download}">
</h:commandButton>
Javascript:
function checkCallBack(data) {
var ajaxStatus = data.status;
switch (ajaxStatus) {
case "begin":
break;
case "complete":
break;
case "success":
document.getElementById('download-form:download-button2').click();
break;
}
}
download-button renders a message area on page and download-button2 triggers a download method. they are two different requests. When the first request completed, the second request will be triggered.

How to count the number of times a h:outputLink was clicked?

I have a PrimeFaces page with following code:
<pm:content id="content">
<p:dataList value="#{likeditems.likedItems}" var="item" pt:data-inset="true" paginator="true" rows="5">
<f:facet name="header">
Products you liked in the past
</f:facet>
<h:outputLink value="#{item.url}" target="_new">
<p:graphicImage name="http://example.com/my-product-mobile/f/op/img/underConstructionImage.jpg" />
<h2>#{item.title}</h2>
<p>Approx. #{item.price} (for most up-to-date price, click on this row and view the vendor's page)</p>
</h:outputLink>
<f:facet name="footer">
Products you liked in the past
</f:facet>
</p:dataList>
</pm:content>
When the user clicks on the h:outputLink, I want 2 things to happen:
A new page with URL item.url is opened in the browser.
Method likeditems.itemLinkClicked(item) is invoked (in that method I update the number of times a particular link was clicked).
First thing is already working (target="_new").
How can I implement the second one (method call for updating the number of times the link was clicked) without the first ceasing to work?
First thing is already working (target="_new").
The target should actually be _blank.
How can I implement the second one (method call for updating the number of times the link was clicked) without the first ceasing to work?
The simplest (naive) JSF-ish way would be triggering a <p:remoteCommand> on click.
<h:outputLink value="#{item.url}" target="_blank" onclick="count_#{item.id}()">
...
</h:outputLink>
<p:remoteCommand name="count_#{item.id}" action="#{likeditems.itemLinkClicked(item)}" />
But this generates lot of duplicate JS code which is not very effective. You could put it outside the data list and fiddle with function arguments. But this still won't work when the enduser rightclicks and chooses a context menu item (open in new tab, new window, new incognito window, save as, copy address, etc). This also won't work when the enduser middleclicks (default browser behavior of middleclick is "open in a new window").
At ZEEF we're using a script which changes the <a href> on click, middleclick or rightclick to an URL which invokes a servlet which updates the count and then does a window.open() on the given URL.
Given a
<h:outputLink value="#{item.url}" styleClass="tracked" target="_blank">
the relevant script should basically look like this:
// Normal click.
$(document).on("click", "a.tracked", function(event) {
var $link = $(this);
updateTrackedLink($link);
var trackingURL = $link.attr("href");
$link.attr("href", $link.data("href"));
$link.removeData("href");
window.open(trackingURL);
event.preventDefault();
});
// Middle click.
$(document).on("mouseup", "a.tracked", function(event) {
if (event.which == 2) {
updateTrackedLink($(this));
}
});
// Right click.
$(document).on("contextmenu", "a.tracked", function(event) {
updateTrackedLink($(this));
});
// Update link href to one of click count servlet, if necessary.
function updateTrackedLink($link) {
if ($link.data("href") == null) {
var url = $link.attr("href");
$link.data("href", url);
$link.attr("href", "/click?url=" + encodeURIComponent(url));
}
}
and the click servlet should look like this (request parameter validation omitted for brevity):
#WebServlet("/click")
public class ClickServlet extends HttpServlet {
#EJB
private ClickService clickService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("url");
clickService.incrementClickCount(url);
response.sendRedirect(url);
}
}
Note that this way the target="_blank" isn't necessary. It would only be used by users who have JavaScript disabled. But then many more other things on the website wouldn't work anyway, including the above JS tracking. It this is also really your concern, then you'd better just put that click servlet URL directly in <h:outputLink value>.

jsf 2 outputlink rendering method call without clicking

I am relatively new in jsf.
I have a jsf page someDetails.xhtml, in which I have an output link
<h:outputLink value="#{someTaskController.completeTask(taskId)}?taskId=#{taskId}">Assign Ticket</h:outputLink>
On clicking on this link, the method completeTask should be called and do something.
The problem is, when the jsf page someDetails.xhtml is opened(in browser), the method completeTask is getting called and does all the task, which should only happen on clicking the link.
What should I do ? Please help
You're using the wrong tag for your purpose, use command link instead:
<h:commandLink value="Assign Ticket" action="#{someTaskController.completeTask()}">
<f:param name="taskId" value="#{taskId}" />
</h:commandLink>
You can access taskId inside method completeTask() like this:
public void completeTask() {
Map<String,String> params =
FacesContext.getExternalContext().getRequestParameterMap();
String taskId= params.get("taskId");
// do your business action...
}

Navigate after successfull action on commandButton

I am building a JSF application using Primefaces mobile (0.9.3 with Primefaces 3.5).
I hava a login page, on this login page there is a login button defined as followed:
<p:commandButton value="#{msg['label.login']}" action="#{loginBean.login}" update="usernameMsg" />
The loginBean.login method is defined as followed:
public String login() {
try {
//do login
return "#loggedInTarget?transition=fade";
} catch (UserNotValidException e) {
//User not valid, display exception
FacesContext
.getCurrentInstance()
.addMessage(
"loginForm:username",
new FacesMessage(
FacesMessage.SEVERITY_ERROR,
"",
messageService
.getMessage("error.message.loginNotSuccessfull")));
}
return null;
}
In my main xhtml (the same in which the button is defined), I have defined the following addtional views:
<pm:view id="registerTarget">
<ui:include
src="/WEB-INF/c52bc19d58a64ae4bd12dec187a2d4b7/register.xhtml" />
</pm:view>
<pm:view id="loggedInTarget">
TEST
</pm:view>
I do it that way because I want to use transitions within Primefaces mobile. To get to the register page I use a p:button which works fine:
<p:button value="#{msg['label.register']}"
href="#registerTarget?transition=fade" />
Why is my login button not working? I also tried to put in "#loggedInTarget?transition=fade" directly as action, but this didn't work either :(
I need the action, because I have to check if the user credentials are valid. If they are valid I want to display my loggedInTarget.
How can I achieve it?
Thanks in advance!
EDIT:
The button is inside a form.
The navigation case outcome value must represent a view ID, not an URL (for sure not a hash fragment). Try with <p:button outcome="...">, and you'll see that it fails over there as well.
Your closest bet is sending a redirect.
public void login() throws IOException {
// ...
externalContext.redirect("#loggedInTarget?transition=fade");
// ...
}
This is also exactly what the <p:button href="..."> does under the covers: causing a GET request on the given URL.

How to display p:fileUpload invalidFileMessage in p:growl

I'm using <p:fileUpload> which is restricted to PDF only. However, the invalidFileMessage shows inside the <p:fileUpload> component. How can I show it in <p:growl> instead?
<p:fileUpload allowTypes="/(\.|\/)(pdf)$/"
invalidFileMessage="File is Invalid. Only PDF files are allowed" />
You can't handle this server side. The file type is validated at client side without hitting any code in server side. So, any suggestions which suggest to manually create FacesMessage and/or explicitly add <p:message(s)> are unthoughtful and untested.
You should use jQuery. It solves everything.
Based on the fileupload.js source code, your best bet is to listen on the fictional show event of the message container and then move the messages container to end of the form.
First extend $.show() to actually trigger the show event.
(function($) {
var originalShowFunction = $.fn.show;
$.fn.show = function() {
this.trigger("show");
return originalShowFunction.apply(this, arguments);
};
})(jQuery);
Then simply create a listener on show event which basically runs when file upload messages appear and then parse every single message and use the renderMessage() function of the <p:growl> JS API. The below example assumes that you've a <p:growl widgetVar="growl"> somewhere in the same page.
$(document).on("show", ".ui-fileupload-content>.ui-messages", function() {
$(this).children().hide().find("li").each(function(index, message) {
var $message = $(message);
PF("growl").renderMessage({
summary: $(".ui-messages-error-summary", $message).text(),
detail: $(".ui-messages-error-detail", $message).text()
});
});
});
Well add an message tag in your page something like:
<p:messages id="test" autoUpdate="true" />
And in fileupload update="#this,test" and your message will be displayed in p:messages. You can change easly in growl works the same.
Look in the primefaces showcase for more examples
Looked up an example in Primefaces showcase and found this. The actual page:
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
allowTypes="/(\.|\/)(pdf)$/"/>
<p:growl id="messages" showDetail="true"/>
And the file uploader controller class:
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
Maybe something to keep in mind on how to display messages in Primefaces

Resources