AEM 6.1提交基本表单并重定向到同一页面

时间:2015-07-16 12:35:27

标签: aem sling sightly

我正在尝试在AEM 6.1上执行以下操作:

  1. 开发一个简单的表格(3个输入字段)
  2. 处理提交的值
  3. 并使用已处理的值/结果重定向到同一页面
  4. 我能够将值提交给servlet,并处理它们(业务逻辑),并将结果提交给requestparamter,以便我可以在UI上检索它们。但我坚持这些:

    1. 重定向到同一页面
    2. 检索请求参数并使用Sightly显示它们。
    3. 代码段: 的Servlet

      @SlingServlet(
      methods = { "POST","GET" }, 
      name="com.tti.tticommons.service.servlets.LeadTimeTrendsServlet",
      paths = { "/services/processFormData" }
      )
      public class TTICommonServlet extends SlingAllMethodsServlet{   
      ...
      @Override
      protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {
        String result;
        try {
              Enumeration<String> parameterNames = request.getParameterNames();
              Map<String, String> formParametersMap = new HashMap<String, String>();
              while (parameterNames.hasMoreElements()) {
                  paramName = parameterNames.nextElement();
                  paramValue = request.getParameter(paramName);
                  .......
                  .......
             }
      
             request.setAttribute("result",result);
      
             response.sendRedirect("/content/ttii/en/**posttest.html**");
          }
      }
      

      任何人都可以请求帮助退休以上的结果&#34;结果&#34;在posttest.html中使用sightly。

2 个答案:

答案 0 :(得分:5)

经过大量的研究和几次试验,我终于让代码工作了。我不得不从stackoverflow中的几个答案中获取相关信息。感谢所有作者。在这里发布我的解决方案对其他人有益。

来自网络服务的响应的结果表单:

enter image description here

流程

  1. 将表单数据提交给Servlet的POST方法
  2. 在Servlet中,从请求中获取用户输入的值
  3. 进行必要的网络服务电话。得到答复(json)
  4. 我将response-json添加为请求
  5. 的参数
  6. 使用Wrapper,转到必要的页面
  7. 定义一个与Sightly一起使用的WCMUse类。
  8. 将“请求”分配给Use-class并在那里处理
  9. 使用来自Use-class的指定值使用sightly
  10. 代码段 - HTML

      <form name="userRegistrationForm" method="post" action="/services/processFormData">
    
    <input type="hidden" name=":redirect" value="posttest.html" />
    <input type="submit" title="Submit" class="btn submit btn-success" value="Submit" tabindex="25" name="bttnAction">
    
    <div data-sly-use.model="${'com.abccommons.service.helpers.PostServiceHelper' @ slingreq=request }">
    **${model.getRawJson}**
    </div>
    

    代码段 - Servlet

    @SlingServlet(
    label = "ABC - Common Servlet", 
    metatype = true, 
    methods = { "POST" }, 
    name="com.abccommons.service.servlets.ABCPostServlet",
    paths = { "/services/processFormData" }
    )
    public class ABCPostServlet extends SlingAllMethodsServlet{ 
    
    @Override
    protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,IOException {  
        log.info("\n\n----- ABCPostServlet POST: ");        
    
        String paramName;
        String paramValue;
        String osgiService="";
    
        try {
            Enumeration<String> parameterNames = request.getParameterNames();
            Map<String, String> formParametersMap = new HashMap<String, String>();
            while (parameterNames.hasMoreElements()) {
                paramName = parameterNames.nextElement();
                paramValue = request.getParameter(paramName);
    
                if (paramName.equals("osgiService")) {
                    osgiService = paramValue;
                } else if (paramName.equals(":cq_csrf_token")) {
                    //TODO: don't add to the map
                } else if (paramName.equals("bttnAction")) {
                    //TODO: dont' add to the map
                } else {
                    //log.info("\n---ParamName="+paramName+", value="+paramValue);
                    formParametersMap.put(paramName, paramValue);                            
                }
            }           
    
            String parametersInJSON = JSONHelper.toJson(formParametersMap);
            log.info("\n\n----------- POST paramters in json="+parametersInJSON);
    
            String json = webServiceHelper.getJSON(osgiService, parametersInJSON, request, response);
            log.info("\n\n----------- POST json from web service="+json);
    
            request.setAttribute("jsonResponse",json);
    
            //String redirectPage =  request.getParameter(":redirect");
            //RequestDispatcher dispatcher = request.getRequestDispatcher("/content/en/"+redirectPage);
            RequestDispatcher dispatcher = request.getRequestDispatcher("/content/en/postformtest.html");
            GetRequest getRequest = new GetRequest(request);
            dispatcher.forward(getRequest, response);            
        } catch (Exception e) {
            log.error("SlingServlet Failed while retrieving resources");
        } finally {
           //TODO
        }         
    }
    
    /** Wrapper class to always return GET for AEM to process the request/response as GET. 
    */
    private static class GetRequest extends SlingHttpServletRequestWrapper {
        public GetRequest(SlingHttpServletRequest wrappedRequest) {
            super(wrappedRequest);
        }
    
        @Override
        public String getMethod() {
            return "GET";
        }
    }    
    

    代码段 - PostServiceHelper - WCMUSe类

    public class PostServiceHelper extends WCMUse {
    protected final Logger log = LoggerFactory.getLogger(PostServiceHelper.class);
    
    private SlingHttpServletRequest httpRequest;
    
    private String rawJson;
    
    @Override
    public void activate() throws Exception {
        log.info("\n\n========= PostServiceHelper.activate():"+get("slingreq", SlingHttpServletRequest.class));
        this.httpRequest = get("slingreq", SlingHttpServletRequest.class);
        //this.resourceResolver = getResourceResolver();        
        //log.info("\n\n========= getRequest()="+getRequest()); 
    
        SlingHttpServletRequest tRequest;
    
        Set<String> keys = new HashSet<String>();
        Enumeration<?> attrNames = this.httpRequest.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attr = (String) attrNames.nextElement();            
            //log.info("\n--- Key="+attr);
    
            if (attr.equals("jsonResponse")) {
                this.setRawJson((String)this.httpRequest.getAttribute(attr));
                //log.info("\n---rawJson is SET with : "+this.rawJson);
            }
        }
    }
    
     public void setRawJson(String json) {
        this.rawJson = json;
    }   
    
    public String getRawJson() {
        return this.rawJson;
    }
    }
    

答案 1 :(得分:1)

这实际上是在Sling中实现的一个相当棘手的模式。通过异步提交表单并通过JavaScript动态更新HTML,可以更好地满足您的需求。

如果您确实需要以指定的方式提交表单,那么您的servlet需要生成HTML响应。要生成由请求路径标识的页面呈现组成的响应,您的servlet需要将请求分派给适当的呈现机制。您可以参考Get JSP output within Servlet in AEM获取有关如何完成此操作的信息。发送后,您的页面及其组件应该可以访问提交的表单值以及请求中设置的属性。