Spring 在 JmsListener 中实例化 IWebContext

Instantiate IWebContext inside JmsListener in Spring

我有一个 Spring 应用程序 运行 作为休息 api。

我们假设在某个时刻,生成了一条包含一些信息的消息并将其存储在 AWS SQS 队列中。

调用 JMSListener 时,我正在尝试使用 thymeleaf 和 openhtmltopdf 生成 pdf 报告。我在实例化 IWebContext 时遇到了麻烦,因为它需要 HttpServletRequest、HttpServletResponse 和 Locale 作为参数。语言环境不是问题,因为我可以将它作为 SQS 消息的一部分包含在内,但我受困于 REQ 和 RES。

我使用的代码:

IWebContext ctx = new WebContext(¿REQUEST?, ¿RESPONSE?, servletContext, locale, mapParams);
String processedHtml = templateEngine.process(template, ctx);

try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
    PdfRendererBuilder builder = new PdfRendererBuilder();
    builder.useSVGDrawer(new BatikSVGDrawer());
    builder.useFastMode();
    builder.withHtmlContent(processedHtml, baseUrl);
    builder.toStream(bos);
    builder.run();
    return bos.toByteArray();
} catch (Exception e) {
    logger.error("xxx");
}

因为它是在@JmsListener(destination = "${aws.sqs.queue.name}") 注释方法中调用的,所以我不能使用以下选项的none:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

因为:

RequestContextHolder.getRequestAttributes()

始终为空。

感谢和问候。

我认为您不应该为此使用 IWebContext。相反,只需使用 org.thymeleaf.context.Context.