有没有人知道将请求参数绑定到adobe cq5(比如spring mvc或其他这样的框架)中的对象的方法?
或者如果没有办法在cq5中直接做到这一点,有没有人集成过第三方框架来做到这一点?

最佳答案

我还没有发现任何与cq5本身绑定的东西。不过,您可以在cq5中使用spring databinder类,我就是这么做的。只需在组件中直接使用org.springframework.web.bind.servletrequestdatabinder类,如下所示:

ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(myModel, "myModel");
dataBinder.bind(slingRequest);

如果需要,可以通过getBindingResult()方法从databinder实例获取org.springframework.validation.bindingResult。此外,还可以配置org.springframework.core.convert.conversionservice,以便通过servletrequestdatabinder setconversionservice(conversionservice)方法使用。
我做的一件事就是绑定吊索后缀。我遵循url后缀中的${key}=${value}模式,以便在使用sling后缀时尽可能利用dispatcher缓存。例如,给定url/content/myapp/en_us/mypage.html/key1=value1/key2=value2.html,我们将后缀解析为{“key1”:“value1”,“key2”:“value2”}的map。可以通过扩展servletrequestdatabinder并重写addbindvalues(mutablepropertyvalues mpvs,servletrequest request)方法来绑定这些值。例如:
public class SlingServletRequestDataBinder extends ServletRequestDataBinder {
  public SlingServletRequestDataBinder(Object target, String objectName) {
    super(target, objectName);
  }

  @Override
  protected void addBindValues(MutablePropertyValues mpvs,
      ServletRequest request) {
    SlingHttpServletRequest slingHttpServletRequest = unwrap(request);

    if (null == slingHttpServletRequest) {
      return;
    }

    String suffix = slingHttpServletRequest.getRequestPathInfo().getSuffix();
    Map<String, String> suffixParameters = // parse suffix into Map here...
    mpvs.addPropertyValues(suffixParameters);

    super.addBindValues(mpvs, request);
  }

  public static SlingHttpServletRequest unwrap(ServletRequest servletRequest) {
    // immediate termination if we found one
    if (servletRequest instanceof SlingHttpServletRequest) {
      return (SlingHttpServletRequest) servletRequest;
    }

    while (servletRequest instanceof ServletRequestWrapper) {
      servletRequest = ((ServletRequestWrapper) servletRequest).getRequest();

      // immediate termination if we found one
      if (servletRequest instanceof SlingHttpServletRequest) {
        return (SlingHttpServletRequest) servletRequest;
      }
    }

    return null;
  }
}

上面的代码应该与sling后缀和url参数结合使用。例如,给定此模型:
public class MyModel {
  private String key1;
  private String key2;
  private String key3;
  // getters and setters go here...
}

还有/content/myapp/en_us/mypage.html/key1=value1/key2=value2.html的url?key3=value3,您的模型将以{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}结束。

09-10 05:50