gpt4 book ai didi

spring-mvc - 在 Thymeleaf 方言处理器中访问 HttpServletRequest 和 HttpServletResponse

转载 作者:行者123 更新时间:2023-12-05 08:56:20 29 4
gpt4 key购买 nike

我正在尝试创建一个执行 ServletDispatcher.include 的 Thymeleaf 方言处理器。我已经扩展了 AbstractElementTagProcessor 并覆盖了 doProcess 方法。相关代码片段为:

@Override
protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {
ServletContext servletContext = null; // TODO: get servlet context
HttpServletRequest request = null; // TODO: get request
HttpServletResponse response = null; // TODO: get response

// Retrieve dispatcher to component JSP view
RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/something");

// Create wrapper (acts as response, but stores output in a CharArrayWriter)
CharResponseWrapper wrapper = new CharResponseWrapper(response);

// Run the include
dispatcher.include(request, wrapper);

String result = wrapper.toString();

// Create a model with the returned string
final IModelFactory modelFactory = context.getModelFactory();
final IModel model = modelFactory.parse(context.getTemplateData(), result);

// Instruct the engine to replace this entire element with the specified model
structureHandler.replaceWith(model, false);

我以前以自定义 JSP 标记的形式编写过类似的代码。问题是:我不知道如何访问 ServletContext、HttpServletRequest 和 HttpServletResponse!这完全可以做到,还是我应该接受 Thymeleaf 太擅长隐藏 HTTP 上下文?

最佳答案

您可以访问请求(通过使用 #request 对象,使您可以直接访问 javax.servlet.http.HttpServletRequest 对象)参数和 session (使用 #session 对象,使您可以直接在 Thymeleaf View 中直接访问 javax.servlet.http.HttpSession 对象)属性:

${#request.getAttribute('foo')}
${#request.getParameter('foo')}
${#request.getContextPath()}
${#request.getRequestName()}

<p th:if="${#request.getParameter('yourParameter') != null
th:text="${#request.getParameter('yourParameter')}"}">Request Param</p>

${#session.getAttribute('foo')}
${#session.id}
${#session.lastAccessedTime}

<p th:if="${session != null}"> th:text="${session.yourAttribute}"</p>

阅读更多 here .

关于spring-mvc - 在 Thymeleaf 方言处理器中访问 HttpServletRequest 和 HttpServletResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41395024/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com