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

2024-03-05

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

  1. 开发一个简单的表单(3 个输入字段)
  2. 处理提交的值,
  3. 并重定向到带有处理后的值/结果的同一页面

我能够将值提交到 servlet,并处理它们(业务逻辑),并将结果发送到 requestparamter,以便我可以在 UI 上检索它们。但我被困在这些:

  1. 重定向到同一页面
  2. 检索请求参数并使用 Sightly 显示它们。

代码片段: 服务程序

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

任何人都可以帮助ho使用sightly在posttest.html中检索上述“结果”。


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

带有网络服务响应的结果表:

工艺流程

  1. 向 Servlet 的 POST 方法提交表单数据
  2. 在Servlet中,从请求中获取用户输入的值
  3. 进行必要的 Web 服务调用。获取响应(json)
  4. 我将response-json作为参数添加到请求中
  5. 使用Wrapper,转发到必要的页面
  6. 定义一个 WCMUse 类以与 Sightly 一起使用。
  7. 将“请求”分配给使用类并在那里处理它
  8. 使用从 Use-class 到 UI 的指定值,使用sightly

代码片段 - 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AEM 6.1 Sightly 基本表单提交并重定向到同一页面 的相关文章

随机推荐