How to validate a field using cq.HTTP.post method In adobe cq5?

安稳与你 提交于 2019-12-02 11:31:47

Since the post doesn't mention the imports , I'm assuming you are using the Citytech Bedrock library's AbstractValidatorServlet. This servlet only overrides the doGet method. The docs say the servlets have to be registered to a resourceType and GET method.

@SlingServlet(resourceTypes = "bedrock/components/content/example", selectors = "validator", extensions = "json", methods = "GET")

The library also have a javascript utility method to call the validator servlet

Bedrock.Utilities.Dialog.validateField(this, value, 'Name is invalid');

The problem is actually that the servlet is expecting a json extension and you are sending none. Look closely at the following definition:

@Property(name = "sling.servlet.extensions", value = "json")

and in your JS function you are calling the url /bin/feeds/validation:

CQ.HTTP.post('/bin/feeds/validation', function(options, success, response){}

So change the url to /bin/feeds/validation.json and it should work. Beside this you are expecting json and you are generating a html output. For building json response, you can use the class com.day.cq.commons.TidyJSONWriter as follows:

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
    final TidyJSONWriter writer = new TidyJSONWriter(response.getWriter());
    response.setContentType("application/json");

    try {
        writer.object();
        writer.key("mykey").value("myvalue");
        writer.endObject();

    } catch(Exception e) {
      //handle the exceptions
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!