1

我正在尝试使用http://code.google.com/p/kaptcha/这看起来是一种包含 CAPTCHA 的非常简单的方法。我的演示应用程序是 JSF,虽然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";
}

但它不理解请求对象:(

4

3 回答 3

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 元素。

于 2009-04-27T10:53:35.537 回答
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);
        }
    }

于 2011-01-12T05:30:24.530 回答
0

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

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



编辑(感谢麦克道尔):

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

于 2009-04-27T06:15:44.033 回答