tags:

views:

463

answers:

2

I'm trying to use http://code.google.com/p/kaptcha/ which looks like a very easy way to include CAPTCHA. My demo app is JSF and although the instructions are simple for JSP, I don't know how to use them in JSF. How do I translate this in JSF?

In your code that manages the submit action:

String kaptchaExpected = (String)request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String kaptchaReceived = request.getParameter("kaptcha");

if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) { setError("kaptcha", "Invalid validation code."); }

I tried putting it in my:

public String button1_action() {
    // TODO: Process the action. 
    return "success";
}

but it doesn't understand the request object :(

A: 

You can retrieve the request object from the JSF External Context, which is accessible from the FacesContext, using the following code:

HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();



Edit (thanks to McDowell) :

Another way is to use the FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap() method to access the request parameters...

romaintaz
An alternative is to use ExternalContext.getRequestParameterMap() to avoid importing the servlet API.
McDowell
+1  A: 

This equivalent JSF action should do it:

  // bind to <h:inputText value="#{thisbean.kaptchaReceived}" />
  private String kaptchaReceived;

  public String getKaptchaReceived() {
    return kaptchaReceived;
  }

  public void setKaptchaReceived(String kaptcha) {
    kaptchaReceived = kaptcha;
  }

  public String button1_action() {
    if (kaptchaReceived != null) {
      FacesContext context = FacesContext
          .getCurrentInstance();
      ExternalContext ext = context.getExternalContext();
      Map<String, Object> session = ext.getSessionMap();
      String kaptchaExpected = session
          .get(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
      if (kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
        return "success";
      }
    }
    return "problem";
  }

This assumes that you want to use h:inputText and h:graphicImage in your JSF view instead of HTML elements.

McDowell