开发者

problem refreshing captcha with ajax

I'm using a captcha in my JSF page (not recaptcha or randomly generated image value, etc). Initially it gets its value from CaptchaServlet. I want to add "refresh image" button without refreshing the whole page, but the code below doesn't work.

<h:panelGrid id="grid" columns="1" style="margin-bottom:10px">
    <h:graphicImage id="capimg" value="#{facesContext.externalContext.requestContextPath}/../Captcha.jpg"/>
</h:panelGrid>

The re开发者_如何学编程fresh button with PrimeFaces <p:commandButton>

<p:commandButton value="This" process="@this" update="grid" onclick="#{facesContext.externalContext.requestContextPath}/../Captcha.jpg"/>

refreshes the whole page.

Do you have any suggestions? Can I use a managed bean and forward to a servlet?


The <p:commandButton> uses Ajax to asynchronously update parts of the page. However, it requires that all necessary JavaScript libraries are included to do all the Ajax works. This should automatically happen when you have a <h:head> instead of a <head> in the master template. The JSF 2.0 resource management will then include the necessary <script> elements in there. If you have read the server logs, you should have noticed warnings that this has failed because the <h:head> is missing.

Here's how a minimum JSF 2.0 Facelet master template should look like, with PrimeFaces taglib declared:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.som/jsf/core"
    xmlns:h="http://java.sun.som/jsf/html"
    xmlns:ui="http://java.sun.som/jsf/facelets"
    xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <title>Page title</title>
    </h:head>
    <h:body>
        <h1>Put your content here</h1>
    </h:body>
</html>

Please note the <h:head> and <h:body> instead of <head> and <body>. Rightclick the generated HTML page in the webbrowser an choose View Source. You should see the included <script> elements in there.


Update: get rid of the onclick attribute. It's not valid JavaScript code. Further you also need to ensure that the servlet response with the image is not cached by the webbrowser. You can do that by adding the following headers before you write any bit to the response:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜