在AEM中的Servlet中获取JSP输出

时间:2015-06-10 07:17:35

标签: java jsp servlets cq5 aem

在CQ中,我们需要在servlet中处理jsp,然后将结果与我们从服务器获得的其他结果合并,然后再写回浏览器。

以下代码几乎是我们需要的,除了它在处理jsp后将结果写回浏览器。

RequestDispatcher dispatcher = request.getRequestDispatcher(resource);
dispatcher.forward(request, response);

我们尝试使用模拟响应如下:

RequestData requestData = new RequestData(slingRequestProcessor, request, mockResponse);
SlingHttpServletRequest slingRequest = requestData.getSlingRequest();
SlingHttpServletResponse slingResponse = requestData.getSlingResponse();
RequestDispatcher dispatcher = request.getRequestDispatcher(resource);
dispatcher.forward(slingRequest, slingResponse);

但是我们遇到了问题。

2 个答案:

答案 0 :(得分:4)

首先关闭 - 根据您的描述,您似乎想要使用requestDispatcher.include而不是requestDispatcher.forward

关于包含响应内容,您传递给requestDispatcher.include调用的响应可能是您自己创建的对象,它会将其输出写入字符串而不是将其返回到浏览器。以下内容可能是恰当的:

final ServletOutputStream outputStream = new ServletOutputStream() {
    public void write(int b) throws IOException {
        outputBuffer.append((char) b);
    }
};

SlingHttpServletResponseWrapper responseWrapper = new SlingHttpServletResponseWrapper(response) {
    public ServletOutputStream getOutputStream() {
        return outputStream;
    }

    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(outputBuffer);
    }

    public SlingHttpServletResponse getSlingResponse() {
        return super.getSlingResponse();
    }
};

包含outputStream.toString()后应提供资源请求执行的结果。

答案 1 :(得分:0)

结合所有反馈,这就是我们提出的:

    //Map<String, Object> jstlValues, final Map<String, Object> propertyValues, String resourceType, SlingHttpServletRequest request, SlingHttpServletResponse response

    final StringWriter outputBuffer = new StringWriter();
    SlingHttpServletResponseWrapper responseWrapper = new SlingHttpServletResponseWrapper(response) {
        public PrintWriter getWriter() throws IOException {
            return new PrintWriter(outputBuffer);
        }

        public SlingHttpServletResponse getSlingResponse() {
            return super.getSlingResponse();
        }
    };

    ResourceMetadata resourceMetaData = new ResourceMetadata();
    resourceMetaData.setResolutionPath("/dummy");
    for (Map.Entry<String, Object> entry: jstlValues.entrySet()) {
        request.setAttribute(entry.getKey(), entry.getValue());
    }

    SyntheticResource resource = new SyntheticResource(request.getResourceResolver(), resourceMetaData, resourceType) {
        public <T> T adaptTo(Class<T> type) { 
             if (type == ValueMap.class) { 
                 ValueMap m = new ValueMapDecorator(propertyValues); 
                 return (T) m; 
             } 
             return super.adaptTo(type); 
         } 
    };
    RequestDispatcher dispatcher = request.getRequestDispatcher(resource);
    dispatcher.include(request, responseWrapper);

    return outputBuffer.toString();