使用kaptcha和JSF

时间:2009-04-26 21:43:31

标签: jsf captcha

我正在尝试使用http://code.google.com/p/kaptcha/,这看起来很容易包含CAPTCHA。我的演示应用程序是JSF,虽然是the instructions are simple用于JSP,但我不知道如何在JSF中使用它们。我如何在JSF中翻译它?

  

在管理提交操作的代码中:

     

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."); }

我试过把它放在我的:

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

但它不理解请求对象:(

3 个答案:

答案 0 :(得分:1)

这个等效的JSF操作应该这样做:

  // 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";
  }

这假设您要在JSF视图中使用h:inputTexth:graphicImage而不是HTML元素。

答案 1 :(得分:1)

实现验证器是验证kaptcha的另一种简单方法。

<h:inputText id="kaptcha" autocomplete="off" required="true">
     <f:validator validatorId="kaptchaValidator" />
</h:inputText>
<h:message for="kaptcha" styleClass="errorMessage"/>

---验证员---

public class KaptchaValidator implements Validator {

@Override
public void validate(FacesContext facesContext, UIComponent uiComponent, Object value) throws ValidatorException {

HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);

        String kaptchaExpected = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

        String kaptchaReceived = (String) value;

        if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)) {
            FacesMessage message = new FacesMessage();

            message.setDetail("Invalid Security Code.");
            message.setSummary("Invalid security code.");
            message.setSeverity(FacesMessage.SEVERITY_INFO);

            throw new ValidatorException(message);
        }
    }

答案 2 :(得分:0)

您可以使用以下代码从可从FacesContext访问的JSF外部上下文中检索请求对象:

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



修改(感谢McDowell):

另一种方法是使用FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()方法访问请求参数...