在Thymeleaf方言处理器中访问HttpServletRequest和HttpServletResponse
我试图创建一个Thymeleaf方言处理器,它执行ServletDispatcher.include。我扩展了AbstractElementTagProcessor并重写了doProcess方法。相关的代码片段是:在Thymeleaf方言处理器中访问HttpServletRequest和HttpServletResponse
@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
对象,让您在javax.servlet.http.HttpSession
对象直接访问)在Thymeleaf观点属性直接:
${#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。
以上是 在Thymeleaf方言处理器中访问HttpServletRequest和HttpServletResponse 的全部内容, 来源链接: utcz.com/qa/262957.html